Zama 백서

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

hint %} ```solidity wrapper.finalizeUnwrap(unwrapRequestId, unwrapAmountCleartext, decryptionProof); ``` This finalizes the unwrap request by sending the corresponding amount of underlying tokens to the `to` defined in the `unwrap` request. It emits an `UnwrapFinalized` event: ```solidity event UnwrapFinalized( address indexed receiver, bytes32 indexed unwrapRequestId, euint64 encryptedAmount, uint64 cleartextAmount ); ``` ### Transfer confidential tokens {% hint style="info" %} #### **Transfer with input proof** Similarly to the unwrap process, transfers can be made with or without an input proof and the encrypted amount must be approved by the ACL for the `msg.sender`. {% endhint %} {% hint style="warning" %} #### **Unsupported `from`** Accounts with a zero balance that have never held tokens cannot be the `from` address in confidential transfers. {% endhint %} {% hint style="info" %} #### **Transferring to a contract** When transferring to a contract that implements `onConfidentialTransferReceived` and that needs to react to the transfer, prefer `confidentialTransferAndCall` (see [Transfer with callback](#transfer-with-callback)) over granting an operator allowance and having the contract pull funds. The callback delivers the tokens and notifies the recipient in a single transaction, avoiding the extra approval step and the standing operator permission. {% endhint %} #### Direct transfer ```solidity wrapper.confidentialTransfer(to, encryptedAmount, inputProof); wrapper.confidentialTransfer(to, encryptedAmount); ``` #### Operator-based transfer ```solidity wrapper.confidentialTransferFrom(from, to, encryptedAmount, inputProof); wrapper.confidentialTransferFrom(from, to, encryptedAmount); ``` Considerations: * `msg.sender` must be `from` or an approved operator for `from`. #### Transfer with callback This is the **recommended** way to move confidential tokens into a contract: it combines the transfer and the recipient notification into a single transaction, so there is no need to grant a standing operator allowance and have the recipient pull the funds. The callback can be used along an ERC-7984 receiver contract. After the transfer, the receiver's `onTransferReceived` callback is invoked. If the callback returns an encrypted `false`, the contract attempts to refund the transferred amount back to the sender. The returned `transferred` ciphertext is a fresh net amount computed from the transfer and any refund attempt. It is only granted as a transient FHE allowance to `msg.sender` for the current transaction, so callers that need to keep using that value later must obtain their own persistent allowance. ```solidity wrapper.confidentialTransferAndCall(to, encryptedAmount, inputProof, callbackData); wrapper.confidentialTransferAndCall(to, encryptedAmount, callbackData); ``` {% hint style="warning" %} ### **Best-effort refund** The refund is best-effort only. A receiver that transfers, burns, or otherwise reduces its balance during the callback can still return `false`, in which case the refund transfers zero tokens. The sender's tokens end up with the recipient rather than being refunded. {% endhint %} #### Operator-based transfer with callback The callback can be used along an ERC-7984 receiver contract. The returned `transferred` ciphertext is also transient-only here: `msg.sender` can use it during the current transaction, but no persistent allowance is granted on that net amount. ```solidity wrapper.confidentialTransferFromAndCall(from, to, encryptedAmount, inputProof, callbackData); wrapper.confidentialTransferFromAndCall(from, to, encryptedAmount, callbackData); ``` Considerations: * `msg.sender` must be `from` or an approved operator for `from`. ### Check the conversion rate and decimals ```solidity uint256 conversionRate = wrapper.rate(); uint8 wrapperDecimals = wrapper.decimals(); ``` **Examples:** | Underlying Decimals | Wrapper Decimals | Rate | Effect | | ------------------- | ---------------- | ----- | ---------------------------- | | 18 | 6 | 10^12 | 1 wrapped = 10^12 underlying | | 6 | 6 | 1 | 1:1 mapping | | 2 | 2 | 1 | 1:1 mapping | ### Check supplies #### Non-confidential total supply The wrapper exposes a non-confidential view of the total supply, computed from the underlying ERC20 balance held by the wrapper contract. This value may be higher than `confidentialTotalSupply()` if tokens are sent directly to the wrapper outside of the wrapping process. {% hint style="info" %} ### **Total Value Shielded (TVS)** This view function is useful for getting a good approximation of the wrapper's Total Value Shielded (TVS). {% endhint %} ```solidity uint256 nonConfidentialSupply = wrapper.inferredTotalSupply(); ``` #### Encrypted (confidential) total supply The actual supply tracked by the confidential token contract, represented as an encrypted value. It is not possible to get the cleartext value of the total supply. ```solidity euint64 encryptedSupply = wrapper.confidentialTotalSupply(); ``` #### Maximum total supply The maximum number of wrapped tokens supported by the encrypted datatype (uint64 limit). If this maximum is exceeded, wrapping new tokens will revert. ```solidity uint256 maxSupply = wrapper.maxTotalSupply(); ``` ## Integration patterns ### Operator system Delegate transfer capabilities with time-based expiration: ```solidity // Grant operator permission until a specific timestamp wrapper.setOperator(operatorAddress, validUntilTimestamp); // Check if an address is an authorized operator bool isAuthorized = wrapper.isOperator(holder, spender); ``` {% hint style="info" %} For moving tokens into a contract that reacts to the transfer, prefer `confidentialTransferAndCall` (see [Transfer with callback](#transfer-with-callback)) over the operator pattern: it delivers the tokens and notifies the recipient in a single transaction without a standing operator allowance. {% endhint %} ### Denylist The wrapper refuses to move tokens for a denied address. Two independent sources are consulted, and three view functions expose them: one per source, plus a combined check. | View function | Answers | | ----------------------------- | ------------------------------------------------------------------------------------------------------------ | | `isBlocked(user)` | Is `user` able to wrap, unwrap or confidentially transfer? | | `isBlockedOnWrapper(user)` | Is `user` able to wrap, unwrap or confidentially transfer, because it is on the **wrapper's own denylist**? | | `isBlockedOnUnderlying(user)` | Is `user` able to wrap, unwrap or confidentially transfer, because it is denied by the **underlying token**? | ```solidity // The general case: can this address transact with the wrapper at all? bool blocked = wrapper.isBlocked(user); // Denied by the wrapper itself bool blockedOnWrapper = wrapper.isBlockedOnWrapper(user); // Denied by the underlying token (e.g. USDT's `getBlackListStatus`) bool blockedOnUnderlying = wrapper.isBlockedOnUnderlying(user); ``` #### `isBlocked` Returns `true` if either source denies `user`, i.e. `isBlockedOnWrapper(user) || isBlockedOnUnderlying(user)`. The wrapper-local list is consulted first, so an address already denied there is reported without any call to the underlying token. #### `isBlockedOnWrapper` Reads the wrapper-local denylist only. It is a plain storage read: it never calls the underlying token and never reverts. #### `isBlockedOnUnderlying` Forwards the query to the underlying token using the configured deny-list selector, and returns `false` when: * the underlying deny-list check is disabled, or * `user` is the zero address, which is exempt so that mints and burns remain possible. Whether the check is enabled, and which selector is used, can be read with: ```solidity wrapper.getUnderlyingDenyListSelector(); ``` Only the owner can change this configuration, via `setUnderlyingDenyListSelector`. {% hint style="warning" %} ### **`isBlocked` and `isBlockedOnUnderlying` can revert** Unlike `isBlockedOnWrapper`, these perform a `staticcall` on the underlying token when the check is enabled. They revert with `UnderlyingDenyListCallFailed` if that call fails, and with `InvalidUnderlyingDenyListResponse` if the returned data is not a 32-byte value. Callers that treat them as infallible views should handle these cases. Note that the same failure would also make a wrap, transfer, or unwrap revert, so a reverting view reflects a genuinely unusable configuration rather than a quirk of the view. {% endhint %} #### Enforcement Both sources are enforced together on every path that moves tokens: `wrap`, the ERC-1363 `onTransferReceived` callback, confidential transfers, `unwrap`, and `finalizeUnwrap`. The checked parties include the sender, the recipient, and the operator when a transfer is made on behalf of another address. `finalizeUnwrap` re-checks the holder, the operator, and the receiver from the original `unwrap` request, so an address that becomes denied between the two steps cannot complete its unwrap. A denied address causes the operation to revert with `WrapperBlockedAddress(user)` when it is on the wrapper-local denylist, or `UnderlyingDenyListedAddress(user)` when it is denied by the underlying token. ### Observers An **observer** is an address that the wrapper owner authorizes to decrypt encrypted amounts on behalf of the wrapper contract. This can be used to meet a reporting or compliance obligation, for example. {% hint style="danger" %} #### **Scope of observer access** The wrapper holds ACL permission on **every** confidential amount handle it writes. An observer inherits that permission through delegation, so it can decrypt: * the confidential balance of every holder, * the confidential total supply, * the amount of every individual transfer, wrap, and unwrap The authorization has no expiration and stays in force until it is revoked. {% endhint %} An observer holds no other privileges. Observer status is never consulted by the wrapper's access control, and the authorization is recorded in the ACL as a decryption delegation. #### Manage observers Only the owner can add or remove an observer. An observer can also step down on its own. ```solidity // Owner: authorize an address to decrypt on behalf of the wrapper wrapper.addObserver(observerAddress); // Owner: revoke that authorization wrapper.removeObserver(observerAddress); // Observer: revoke your own authorization wrapper.renounceObserver(); ``` Considerations: * `addObserver` and `removeObserver` revert with `OwnableUnauthorizedAccount` for any caller other than the owner. * `addObserver` rejects the zero address, the wrapper itself, and `WILDCARD_CONTRACT`, reverting with `InvalidObserver`. * `addObserver` reverts with `ObserverAlreadyConfigured` if the address is already an observer. * `removeObserver` and `renounceObserver` are no-ops when the address is not an observer: they emit nothing and do not revert, so a governance batch containing `removeObserver` still succeeds if the observer renounced first. * The ACL accepts at most one authorization change per block for a given wrapper and observer pair, so removing and re-adding the same observer within a single block reverts. #### Read the observer set The observer set is public and can be read by anyone. ```solidity // Check a single address bool authorized = wrapper.isObserver(observerAddress); // Read the full set address[] memory allObservers = wrapper.observers(); // Or enumerate it uint256 total = wrapper.observerCount(); address firstObserver = wrapper.observerAt(0); ``` `observerAt` reverts if `index` is greater than or equal to `observerCount()`. The ordering is not stable: removing an observer moves the last entry into the freed slot. #### Seed observers at deployment Observers can be configured up front rather than added afterwards. The `initialize` function takes an `initialObservers` array, and `reinitializeV4` takes the same array when an existing proxy is upgraded. Both revert with `ObserverAlreadyConfigured` if the array contains a duplicate entry. Pass an empty array to deploy or upgrade with no observers. #### Seed the pauser at deployment The pauser can also be set up front instead of through a separate `setPauser` transaction: `initialize` and `reinitializeV4` both take a trailing `pauser_` argument, emit `PauserUpdated`, and leave the wrapper unpaused. Passing `address(0)` deploys (or upgrades) with pausing disabled. ### Query ongoing unwrap request details ```solidity // Get the encrypted amount associated with an ongoing unwrap request euint64 encryptedAmount = wrapper.unwrapAmount(unwrapRequestId); // Get the receiver address of an ongoing unwrap request // Returns address(0) if the ID is not associated with an ongoing request address receiver = wrapper.unwrapRequester(unwrapRequestId); ``` ### Amount disclosure Optionally reveal encrypted amounts publicly: ```solidity // Request disclosure (initiates async decryption) wrapper.requestDiscloseEncryptedAmount(encryptedAmount); // Complete disclosure with proof wrapper.discloseEncryptedAmount(encryptedAmount, cleartextAmount, decryptionProof); ``` ### Check ACL permissions Before using encrypted amounts in transactions, callers must be authorized: ```solidity require(FHE.isAllowed(encryptedAmount, msg.sender), "Unauthorized"); ``` Transfer functions with `euint64` (not `externalEuint64`) require the caller to already have ACL permission for that ciphertext. More information in the [FHEVM library documentation](https://docs.zama.org/protocol/protocol/overview/library#access-control). ## Architecture ``` ┌─────────────────────────────────────────────────────────────────┐ │ ConfidentialWrapper │ │ (UUPS Upgradeable, Ownable2Step) │ ├─────────────────────────────────────────────────────────────────┤ │ ERC7984ERC20WrapperUpgradeable │ │ (Wrapping/Unwrapping Logic, ERC1363 Receiver) │ ├─────────────────────────────────────────────────────────────────┤ │ ERC7984Upgradeable │ │ (Confidential Token Standard - Encrypted Balances/Transfers) │ ├─────────────────────────────────────────────────────────────────┤ │ ZamaMultiChainConfigUpgradeable │ │ (FHE Coprocessor Configuration) │ └─────────────────────────────────────────────────────────────────┘ ``` ## Events | Event | Description | | ------------------------------------------------------------------------------ | ----------------------------------------------- | | `Wrap(to, roundedAmount, encryptedWrappedAmount)` | Emitted when tokens are wrapped | | `ConfidentialTransfer(from, to, encryptedAmount)` | Emitted on every transfer (including mint/burn) | | `OperatorSet(holder, operator, until)` | Emitted when operator permissions change | | `UnwrapRequested(receiver, unwrapRequestId, encryptedAmount)` | Emitted when unwrap is initiated | | `UnwrapFinalized(receiver, unwrapRequestId, encryptedAmount, cleartextAmount)` | Emitted when unwrap completes | | `AmountDiscloseRequested(encryptedAmount, requester)` | Emitted when disclosure is requested | | `AmountDisclosed(encryptedAmount, cleartextAmount)` | Emitted when amount is publicly disclosed | | `ObserverAdded(observer)` | Emitted when an observer is authorized | | `ObserverRemoved(observer)` | Emitted when an observer is revoked | ## Errors | Error | Cause | | ------------------------------------------------------- | ------------------------------------------------------------------------ | | `ERC7984InvalidReceiver(receiver)` | Transfer to zero address | | `ERC7984InvalidSender(sender)` | Transfer from zero address | | `ERC7984UnauthorizedSpender(holder, spender)` | Caller not authorized as operator | | `ERC7984UnauthorizedUseOfEncryptedAmount(amount, user)` | Caller lacks ACL permission for ciphertext | | `ERC7984UnauthorizedCaller(caller)` | Invalid caller for operation | | `InvalidUnwrapRequest(unwrapRequestId)` | Finalizing non-existent unwrap request | | `ERC7984TotalSupplyOverflow()` | Minting would exceed uint64 max | | `WrapperBlockedAddress(user)` | Address is on the wrapper-local denylist | | `UnderlyingDenyListedAddress(user)` | Address is denied by the underlying token | | `UnderlyingDenyListCallFailed()` | The deny-list `staticcall` on the underlying token failed | | `InvalidUnderlyingDenyListResponse()` | The underlying deny-list call did not return a 32-byte value | | `InvalidObserver(observer)` | Observer is the zero address, the wrapper itself, or `WILDCARD_CONTRACT` | | `ObserverAlreadyConfigured(observer)` | Adding an address that is already an observer | ## Important Considerations ### Ciphertext uniqueness assumption The unwrap mechanism stores requests in a mapping keyed by ciphertext and the current implementation assumes these ciphertexts are unique. This holds in this very specific case but be aware of this architectural decision as it is **NOT** true in the general case. ### Maximum number of decimals The maximum number of decimals `_maxDecimals()` for the confidential token is currently set to **6 decimals** only. This is due to FHE limitations as confidential balances must be represented by the euint64 encrypted datatype. At deployment, the confidential wrapper sets its number of decimals as: * the number of decimals of the underlying token if it is less than `_maxDecimals()` * `_maxDecimals()` otherwise **Example with `_maxDecimals()` set to 6** | Underlying Decimals | Wrapper Decimals | Example | | ------------------- | ---------------- | ---------- | | 18 | 6 | ZAMA/cZAMA | | 6 | 6 | USDT/cUSDT | | 2 | 2 | GUSD/cGUSD | Once a confidential wrapper contract is deployed, this number cannot be updated. It can be viewed with the following view function: ```solidity wrapper.decimals(); ``` ### Maximum total supply The maximum total supply for the confidential token is currently set to `type(uint64).max` (`2^64 - 1`) due to FHE limitations. Avoid wrapping tokens with a very large total supply. Because the limit applies to the confidential token's smallest units, a wrapper with the default 6 decimals can represent at most approximately 18.4 trillion whole tokens. For example, this is only about 3% of SHIB's approximately 590 trillion-token supply, so the wrapper cannot accommodate the entire supply. ### Non-standard token types The wrapper assumes the full transfer amount is received when minting. Tokens that deviate from this assumption, or whose supply changes independently of wrap/unwrap operations, are not supported and may result in undercollateralization or loss of yield. | Type | Behavior | Example | Wrapper impact | | ------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Fee-on-transfer** | A fee is deducted from the transferred amount | SafeMoon, PAXG | The wrapper mints more shares than the underlying balance it receives, leading to undercollateralization | | **Deflationary** | Token supply decreases over time via burns on transfer or scheduled reductions | BOMB | Equivalent to fee-on-transfer; the same undercollateralization risk applies | | **Inflationary** | New tokens are minted over time to addresses other than existing holders | Governance tokens with scheduled emissions | **Supported**: The wrapper is not directly impacted, but holders of the confidential token are subject to the same dilution as holders of the underlying token | | **Rebasing (up)** | Holder balances increase automatically over time to distribute yield | aUSDC, stETH | Yield accrues to the wrapper contract rather than to individual holders; wrapped positions do not earn rewards | | **Rebasing (down)** | Holder balances decrease automatically, for example due to slashing | stETH (slashing) | The wr
프로젝트로 돌아가기