From 6b0507d28e209d4f0ab16ec6f76c8436781f33b6 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Wed, 18 Sep 2024 15:39:52 -0600 Subject: [PATCH 01/13] add WFLOWTokenHandler definition --- .../bridge/FlowEVMBridgeHandlers.cdc | 234 +++++++++++++++++- .../contracts/bridge/FlowEVMBridgeUtils.cdc | 2 +- 2 files changed, 233 insertions(+), 3 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index ebe1e9a8..93d760a5 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -1,6 +1,7 @@ import "Burner" import "FungibleToken" import "NonFungibleToken" +import "FlowToken" import "EVM" @@ -191,6 +192,224 @@ access(all) contract FlowEVMBridgeHandlers { } } + /// Facilitates moving Flow between Cadence and EVM as WFLOW. Since WFLOW is an artifact of the EVM ecosystem, + /// wrapping the native token as an ERC20, it does not have a place in Cadence's fungible token ecosystem. + /// Given the native interface on EVM.CadenceOwnedAccount and EVM.EVMAddress to move FLOW between Cadence and EVM, + /// this handler treats requests to bridge FLOW as WFLOW as a special case. + /// + access(all) resource WFLOWTokenHandler : FlowEVMBridgeHandlerInterfaces.TokenHandler { + /// Flag determining if request handling is enabled + access(self) var enabled: Bool + /// The Cadence Type this handler fulfills requests for. This field is optional in the event the Cadence token + /// contract address is not yet known but the EVM Address must still be filtered via Handler to prevent the + /// contract from being onboarded otherwise. + access(self) var targetType: Type + /// The EVM contract address this handler fulfills requests for. + access(self) var targetEVMAddress: EVM.EVMAddress + + init(wflowEVMAddress: EVM.EVMAddress) { + self.enabled = false + self.targetType = Type<@FlowToken.Vault>() + self.targetEVMAddress = wflowEVMAddress + } + + /// Returns whether the Handler is enabled + access(all) view fun isEnabled(): Bool { + return self.enabled + } + /// Returns the Cadence type handled by the Handler, nil if not set + access(all) view fun getTargetType(): Type? { + return self.targetType + } + /// Returns the EVM address handled by the Handler, nil if not set + access(all) view fun getTargetEVMAddress(): EVM.EVMAddress? { + return self.targetEVMAddress + } + /// Returns nil as this handler simply unwraps WFLOW to FLOW + access(all) view fun getExpectedMinterType(): Type? { + return nil + } + + /* --- TokenHandler --- */ + + /// Fulfill a request to bridge tokens from Cadence to EVM, burning the provided Vault and transferring from + /// EVM escrow to the named recipient. Assumes any fees are handled by the caller within the bridge contracts + /// + /// @param tokens: The Vault containing the tokens to bridge + /// @param to: The EVM address to transfer the tokens to + /// + access(account) + fun fulfillTokensToEVM( + tokens: @{FungibleToken.Vault}, + to: EVM.EVMAddress + ) { + pre { + tokens.getType() == Type<@FlowToken.Vault>(): + "Invalid token type=".concat(tokens.getType().identifier) + .concat(" - WFLOWTokenHandler only handles FlowToken Vault") + } + let flowVault <- tokens as! @FlowToken.Vault + let wflowAddress = self.getTargetEVMAddress()! + + // Get balance from vault + let balance = flowVault.balance + let uintAmount = FlowEVMBridgeUtils.convertCadenceAmountToERC20Amount(balance, erc20Address: wflowAddress) + + // Deposit to bridge COA + let coa = FlowEVMBridgeUtils.borrowCOA() + coa.deposit(from: <-flowVault) + + let preBalance = FlowEVMBridgeUtils.balanceOf(owner: coa.address(), evmContractAddress: wflowAddress) + + // Wrap the deposited FLOW as WFLOW, giving the bridge COA the necessary WFLOW to transfer + let wrapResult = FlowEVMBridgeUtils.call( + signature: "deposit()", + targetEVMAddress: wflowAddress, + args: [], + gasLimit: FlowEVMBridgeConfig.gasLimit, + value: balance + ) + assert(wrapResult.status == EVM.Status.successful, message: "Failed to wrap FLOW as WFLOW") + + let postBalance = FlowEVMBridgeUtils.balanceOf(owner: coa.address(), evmContractAddress: wflowAddress) + + // Cover underflow + assert( + postBalance > preBalance, + message: "Balance decremented after wrapping FLOW" + ) + // Confirm bridge COA's WFLOW balance has incremented by the expected amount + assert( + postBalance - preBalance == uintAmount, + message: "Balance after wrapping FLOW does not match requested amount - expected=" + .concat((preBalance + uintAmount).toString()) + .concat(" actual=") + .concat((postBalance - preBalance).toString()) + ) + + // Transfer WFLOW to recipient + FlowEVMBridgeUtils.mustTransferERC20(to: to, amount: uintAmount, erc20Address: wflowAddress) + } + + /// Fulfill a request to bridge tokens from EVM to Cadence, minting the provided amount of tokens in Cadence + /// and transferring from the named owner to bridge escrow in EVM. + /// + /// @param owner: The EVM address of the owner of the tokens. Should also be the caller executing the protected + /// transfer call. + /// @param type: The type of the asset being bridged + /// @param amount: The amount of tokens to bridge + /// + /// @return The minted Vault containing the the requested amount of Cadence tokens + /// + access(account) + fun fulfillTokensFromEVM( + owner: EVM.EVMAddress, + type: Type, + amount: UInt256, + protectedTransferCall: fun (): EVM.Result + ): @{FungibleToken.Vault} { + let wflowAddress = self.getTargetEVMAddress()! + + // Convert the amount to a UFix64 + let ufixAmount = FlowEVMBridgeUtils.convertERC20AmountToCadenceAmount( + amount, + erc20Address: wflowAddress + ) + assert(ufixAmount > 0.0, message: "Amount to bridge must be greater than 0") + + // Transfers WFLOW to bridge COA as escrow + FlowEVMBridgeUtils.mustEscrowERC20( + owner: owner, + amount: amount, + erc20Address: wflowAddress, + protectedTransferCall: protectedTransferCall + ) + + // Get the bridge COA's FLOW balance before unwrapping WFLOW + let coa = FlowEVMBridgeUtils.borrowCOA() + let preBalance = coa.balance().attoflow + + // Unwrap the transferred WFLOW to FLOW, giving the bridge COA the necessary FLOW to withdraw from EVM + let unwrapResult = FlowEVMBridgeUtils.call( + signature: "withdraw(uint)", + targetEVMAddress: wflowAddress, + args: [UInt(amount)], + gasLimit: FlowEVMBridgeConfig.gasLimit, + value: 0.0 + ) + assert(unwrapResult.status == EVM.Status.successful, message: "Failed to unwrap WFLOW as FLOW") + + let postBalance = coa.balance().attoflow + + // Cover underflow + assert( + postBalance > preBalance, + message: "Balance decremented after unwrapping WFLOW" + ) + // Confirm bridge COA's FLOW balance has incremented by the expected amount + assert( + UInt256(postBalance - preBalance) == amount, + message: "Balance after unwrapping WFLOW does not match requested amount - expected=" + .concat((UInt256(preBalance) + amount).toString()) + .concat(" actual=") + .concat((postBalance - preBalance).toString()) + ) + + // Withdraw FLOW from bridge COA + let withdrawBalance = EVM.Balance(attoflow: UInt(amount)) + assert( + UInt256(withdrawBalance.attoflow) == amount, + message: "Balance failed to convert to attoflow - expected=" + .concat(amount.toString()) + .concat(" actual=") + .concat(withdrawBalance.attoflow.toString()) + ) + let flowVault <- coa.withdraw(balance: withdrawBalance) + assert( + flowVault.balance == ufixAmount, + message: "Vault balance does not match requested amount - expected=" + .concat(ufixAmount.toString()) + .concat(" actual=") + .concat(flowVault.balance.toString()) + ) + return <-flowVault + } + + /* --- Admin --- */ + + /// Sets the target type for the handler + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun setTargetType(_ type: Type) { + panic("WFLOWTokenHandler has targetType set at initialization") + } + + /// Sets the target EVM address for the handler + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun setTargetEVMAddress(_ address: EVM.EVMAddress) { + panic("WFLOWTokenHandler has EVMAddress set at initialization") + } + + /// Sets the target type for the handler + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun setMinter(_ minter: @{FlowEVMBridgeHandlerInterfaces.TokenMinter}) { + panic("WFLOWTokenHandler does not utilize a minter") + } + + /// Enables the handler for request handling. The + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun enableBridging() { + self.enabled = true + } + + /* --- Internal --- */ + + /// Returns an entitled reference to the encapsulated minter resource + access(self) + view fun borrowMinter(): auth(FlowEVMBridgeHandlerInterfaces.Mint) &{FlowEVMBridgeHandlerInterfaces.TokenMinter}? { + return nil + } + } + /// This resource enables the configuration of Handlers. These Handlers are stored in FlowEVMBridgeConfig from which /// further setting and getting can be executed. /// @@ -207,15 +426,26 @@ access(all) contract FlowEVMBridgeHandlers { handlerType: Type, targetType: Type, targetEVMAddress: EVM.EVMAddress?, - expectedMinterType: Type + expectedMinterType: Type? ) { switch handlerType { case Type<@CadenceNativeTokenHandler>(): + assert( + expectedMinterType != nil, + message: "CadenceNativeTokenHandler requires an expected minter type but received nil" + ) let handler <-create CadenceNativeTokenHandler( targetType: targetType, targetEVMAddress: targetEVMAddress, - expectedMinterType: expectedMinterType + expectedMinterType: expectedMinterType! + ) + FlowEVMBridgeConfig.addTokenHandler(<-handler) + case Type<@WFLOWTokenHandler>(): + assert( + targetEVMAddress != nil, + message: "WFLOWTokenHandler requires a target EVM address but received nil" ) + let handler <-create WFLOWTokenHandler(wflowEVMAddress: targetEVMAddress!) FlowEVMBridgeConfig.addTokenHandler(<-handler) default: panic("Invalid Handler type requested") diff --git a/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc b/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc index 1625497f..e5e35ad6 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc @@ -1039,7 +1039,7 @@ contract FlowEVMBridgeUtils { /// Enables other bridge contracts to orchestrate bridge operations from contract-owned COA /// access(account) - view fun borrowCOA(): auth(EVM.Call) &EVM.CadenceOwnedAccount { + view fun borrowCOA(): auth(EVM.Call, EVM.Withdraw) &EVM.CadenceOwnedAccount { return self.account.storage.borrow( from: FlowEVMBridgeConfig.coaStoragePath ) ?? panic("Could not borrow COA reference") From a8dbbe8854952e36f6e0c3b42f08c4a460dd88a0 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Wed, 18 Sep 2024 17:42:43 -0600 Subject: [PATCH 02/13] update FlowEVMBridgeConfig init block --- cadence/contracts/bridge/FlowEVMBridgeConfig.cdc | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc b/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc index 5818569d..3a6c1e0d 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc @@ -428,16 +428,8 @@ contract FlowEVMBridgeConfig { self.gasLimit = 15_000_000 self.paused = true - // Although $FLOW does not have ERC20 address, we associate the the Vault with the EVM address from which - // EVM transfers originate - // See FLIP #223 - https://github.com/onflow/flips/pull/225 - let flowOriginationAddress = EVM.EVMAddress( - bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0] - ) - let flowVaultType = Type<@FlowToken.Vault>() - let flowOriginationAddressHex = flowOriginationAddress.toString() - self.registeredTypes = { flowVaultType: TypeEVMAssociation(associated: flowOriginationAddress) } - self.evmAddressHexToType = { flowOriginationAddressHex: flowVaultType } + self.registeredTypes = {} + self.evmAddressHexToType = {} self.typeToTokenHandlers <- {} From 1da5a879ff981f7ed4efc9cd89ed91d3e9d2b94f Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Wed, 18 Sep 2024 17:43:48 -0600 Subject: [PATCH 03/13] remove checks on FlowToken Vault type from bridge --- cadence/contracts/bridge/FlowEVMBridge.cdc | 8 -------- cadence/tests/test_helpers.cdc | 7 +++++++ 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridge.cdc b/cadence/contracts/bridge/FlowEVMBridge.cdc index 0f83a2bf..71035f6e 100644 --- a/cadence/contracts/bridge/FlowEVMBridge.cdc +++ b/cadence/contracts/bridge/FlowEVMBridge.cdc @@ -69,8 +69,6 @@ contract FlowEVMBridge : IFlowEVMNFTBridge, IFlowEVMTokenBridge { fun onboardByType(_ type: Type, feeProvider: auth(FungibleToken.Withdraw) &{FungibleToken.Provider}) { pre { !FlowEVMBridgeConfig.isPaused(): "Bridge operations are currently paused" - type != Type<@FlowToken.Vault>(): - "$FLOW cannot be bridged via the VM bridge - use the CadenceOwnedAccount interface" self.typeRequiresOnboarding(type) == true: "Onboarding is not needed for this type" FlowEVMBridgeUtils.typeAllowsBridging(type): "This type is not supported as defined by the project's development team" @@ -351,11 +349,6 @@ contract FlowEVMBridge : IFlowEVMNFTBridge, IFlowEVMTokenBridge { /* Handle $FLOW requests via EVM interface & return */ // let vaultType = vault.getType() - if vaultType == Type<@FlowToken.Vault>() { - let flowVault <-vault as! @FlowToken.Vault - to.deposit(from: <-flowVault) - return - } // Gather the vault balance before acting on the resource let vaultBalance = vault.balance @@ -444,7 +437,6 @@ contract FlowEVMBridge : IFlowEVMNFTBridge, IFlowEVMTokenBridge { pre { !FlowEVMBridgeConfig.isPaused(): "Bridge operations are currently paused" !type.isSubtype(of: Type<@{NonFungibleToken.Collection}>()): "Mixed asset types are not yet supported" - !type.isInstance(Type<@FlowToken.Vault>()): "Must use the CadenceOwnedAccount interface to bridge $FLOW from EVM" self.typeRequiresOnboarding(type) == false: "FungibleToken must first be onboarded" FlowEVMBridgeConfig.isTypePaused(type) == false: "Bridging is currently paused for this token" } diff --git a/cadence/tests/test_helpers.cdc b/cadence/tests/test_helpers.cdc index 5b165bdc..5a647380 100644 --- a/cadence/tests/test_helpers.cdc +++ b/cadence/tests/test_helpers.cdc @@ -25,6 +25,8 @@ access(all) let compiledERC20Bytecode = "6101606040523480156200001257600080fd5b5 access(all) let evmBridgeRouterCode = "696d706f727420224e6f6e46756e6769626c65546f6b656e220a696d706f7274202246756e6769626c65546f6b656e220a696d706f72742022466c6f77546f6b656e220a0a696d706f7274202245564d220a0a696d706f7274202249466c6f7745564d4e4654427269646765220a696d706f7274202249466c6f7745564d546f6b656e427269646765220a0a2f2f2f205468697320636f6e747261637420646566696e65732061206d656368616e69736d20666f7220726f7574696e67206272696467652072657175657374732066726f6d207468652045564d20636f6e747261637420746f2074686520466c6f772d45564d206272696467652061732077656c6c0a2f2f2f206173207570646174696e67207468652064657369676e617465642062726964676520616464726573730a2f2f2f0a61636365737328616c6c290a636f6e74726163742045564d427269646765526f75746572207b0a0a202020202f2f2f20456e7469746c656d656e7420616c6c6f77696e6720666f72207570646174657320746f2074686520526f757465720a2020202061636365737328616c6c2920656e7469746c656d656e7420526f7574657241646d696e0a0a202020202f2f2f20456d69747465642069662f7768656e207468652062726964676520636f6e74726163742074686520726f75746572206469726563747320746f20697320757064617465640a2020202061636365737328616c6c29206576656e7420427269646765436f6e74726163745570646174656428616464726573733a20416464726573732c206e616d653a20537472696e67290a202020200a202020202f2f2f204272696467654163636573736f7220696d706c656d656e746174696f6e2075736564206279207468652045564d20636f6e747261637420746f20726f757465206272696467652063616c6c73206265747765656e20564d730a202020202f2f2f0a2020202061636365737328616c6c290a202020207265736f7572636520526f75746572203a2045564d2e4272696467654163636573736f72207b0a20202020202020202f2f2f2041646472657373206f66207468652062726964676520636f6e74726163740a202020202020202061636365737328616c6c292076617220627269646765416464726573733a20416464726573730a20202020202020202f2f2f204e616d65206f66207468652062726964676520636f6e74726163740a202020202020202061636365737328616c6c292076617220627269646765436f6e74726163744e616d653a20537472696e670a0a2020202020202020696e697428616464726573733a20416464726573732c206e616d653a20537472696e6729207b0a20202020202020202020202073656c662e62726964676541646472657373203d20616464726573730a20202020202020202020202073656c662e627269646765436f6e74726163744e616d65203d206e616d650a20202020202020207d0a0a20202020202020202f2f2f2050617373657320616c6f6e672074686520627269646765207265717565737420746f206465646963617465642062726964676520636f6e74726163740a20202020202020202f2f2f0a20202020202020202f2f2f2040706172616d206e66743a20546865204e465420746f206265206272696467656420746f2045564d0a20202020202020202f2f2f2040706172616d20746f3a205468652061646472657373206f66207468652045564d206163636f756e7420746f2072656365697665207468652062726964676564204e46540a20202020202020202f2f2f2040706172616d2066656550726f76696465723a2041207265666572656e636520746f20612046756e6769626c65546f6b656e2050726f76696465722066726f6d20776869636820746865206272696467696e67206665652069732077697468647261776e20696e2024464c4f570a20202020202020202f2f2f0a20202020202020206163636573732845564d2e427269646765290a202020202020202066756e206465706f7369744e4654280a2020202020202020202020206e66743a20407b4e6f6e46756e6769626c65546f6b656e2e4e46547d2c0a202020202020202020202020746f3a2045564d2e45564d416464726573732c0a20202020202020202020202066656550726f76696465723a20617574682846756e6769626c65546f6b656e2e57697468647261772920267b46756e6769626c65546f6b656e2e50726f76696465727d0a202020202020202029207b0a20202020202020202020202073656c662e626f72726f7742726964676528292e6272696467654e4654546f45564d28746f6b656e3a203c2d6e66742c20746f3a20746f2c2066656550726f76696465723a2066656550726f7669646572290a20202020202020207d0a0a20202020202020202f2f2f2050617373657320616c6f6e672074686520627269646765207265717565737420746f20746865206465646963617465642062726964676520636f6e74726163742c2072657475726e696e67207468652062726964676564204e46540a20202020202020202f2f2f0a20202020202020202f2f2f2040706172616d2063616c6c65723a2041207265666572656e636520746f2074686520434f412077686963682063757272656e746c79206f776e7320746865204e465420696e2045564d0a20202020202020202f2f2f2040706172616d20747970653a2054686520436164656e63652074797065206f6620746865204e465420746f20626520627269646765642066726f6d2045564d0a20202020202020202f2f2f2040706172616d2069643a20546865204944206f6620746865204e465420746f20626520627269646765642066726f6d2045564d0a20202020202020202f2f2f2040706172616d2066656550726f76696465723a2041207265666572656e636520746f20612046756e6769626c65546f6b656e2050726f76696465722066726f6d20776869636820746865206272696467696e67206665652069732077697468647261776e20696e2024464c4f570a20202020202020202f2f2f0a20202020202020202f2f2f204072657475726e205468652062726964676564204e46540a20202020202020202f2f2f0a20202020202020206163636573732845564d2e427269646765290a202020202020202066756e2077697468647261774e4654280a20202020202020202020202063616c6c65723a20617574682845564d2e43616c6c29202645564d2e436164656e63654f776e65644163636f756e742c0a202020202020202020202020747970653a20547970652c0a20202020202020202020202069643a2055496e743235362c0a20202020202020202020202066656550726f76696465723a20617574682846756e6769626c65546f6b656e2e57697468647261772920267b46756e6769626c65546f6b656e2e50726f76696465727d0a2020202020202020293a20407b4e6f6e46756e6769626c65546f6b656e2e4e46547d207b0a2020202020202020202020206c657420627269646765203d2073656c662e626f72726f7742726964676528290a2020202020202020202020202f2f20446566696e6520612063616c6c6261636b2066756e6374696f6e2c20656e61626c696e67207468652062726964676520746f20616374206f6e2074686520657068656d6572616c20434f41207265666572656e636520696e2073636f70650a202020202020202020202020766172206578656375746564203d2066616c73650a20202020202020202020202066756e2063616c6c6261636b28293a2045564d2e526573756c74207b0a20202020202020202020202020202020707265207b0a20202020202020202020202020202020202020202165786563757465643a202243616c6c6261636b2063616e206f6e6c79206265206578656375746564206f6e6365220a202020202020202020202020202020207d0a20202020202020202020202020202020706f7374207b0a202020202020202020202020202020202020202065786563757465643a202243616c6c6261636b206d757374206265206578656375746564220a202020202020202020202020202020207d0a202020202020202020202020202020206578656375746564203d20747275650a2020202020202020202020202020202072657475726e2063616c6c65722e63616c6c280a2020202020202020202020202020202020202020746f3a206272696467652e6765744173736f63696174656445564d4164647265737328776974683a2074797065290a2020202020202020202020202020202020202020202020203f3f2070616e696328224e6f2045564d2061646472657373206173736f6369617465642077697468207479706522292c0a2020202020202020202020202020202020202020646174613a2045564d2e656e636f6465414249576974685369676e6174757265280a20202020202020202020202020202020202020202020202022736166655472616e7366657246726f6d28616464726573732c616464726573732c75696e7432353629222c0a2020202020202020202020202020202020202020202020205b63616c6c65722e6164647265737328292c206272696467652e676574427269646765434f4145564d4164647265737328292c2069645d0a2020202020202020202020202020202020202020292c0a20202020202020202020202020202020202020206761734c696d69743a2031353030303030302c0a202020202020202020202020202020202020202076616c75653a2045564d2e42616c616e6365286174746f666c6f773a2030290a20202020202020202020202020202020290a2020202020202020202020207d0a2020202020202020202020202f2f2045786563757465207468652062726964676520726571756573740a20202020202020202020202072657475726e203c2d206272696467652e6272696467654e465446726f6d45564d280a202020202020202020202020202020206f776e65723a2063616c6c65722e6164647265737328292c0a20202020202020202020202020202020747970653a20747970652c0a2020202020202020202020202020202069643a2069642c0a2020202020202020202020202020202066656550726f76696465723a2066656550726f76696465722c0a2020202020202020202020202020202070726f7465637465645472616e7366657243616c6c3a2063616c6c6261636b0a202020202020202020202020290a20202020202020207d0a0a20202020202020202f2f2f2050617373657320616c6f6e672074686520627269646765207265717565737420746f206465646963617465642062726964676520636f6e74726163740a20202020202020202f2f2f0a20202020202020202f2f2f2040706172616d207661756c743a205468652066756e6769626c6520746f6b656e207661756c7420746f206265206272696467656420746f2045564d0a20202020202020202f2f2f2040706172616d20746f3a205468652061646472657373206f66207468652045564d206163636f756e7420746f207265636569766520746865206272696467656420746f6b656e730a20202020202020202f2f2f2040706172616d2066656550726f76696465723a2041207265666572656e636520746f20612046756e6769626c65546f6b656e2050726f76696465722066726f6d20776869636820746865206272696467696e67206665652069732077697468647261776e20696e2024464c4f570a20202020202020202f2f2f0a20202020202020206163636573732845564d2e427269646765290a202020202020202066756e206465706f736974546f6b656e73280a2020202020202020202020207661756c743a20407b46756e6769626c65546f6b656e2e5661756c747d2c0a202020202020202020202020746f3a2045564d2e45564d416464726573732c0a20202020202020202020202066656550726f76696465723a20617574682846756e6769626c65546f6b656e2e57697468647261772920267b46756e6769626c65546f6b656e2e50726f76696465727d0a202020202020202029207b0a20202020202020202020202073656c662e626f72726f7742726964676528292e627269646765546f6b656e73546f45564d287661756c743a203c2d7661756c742c20746f3a20746f2c2066656550726f76696465723a2066656550726f7669646572290a20202020202020207d0a0a20202020202020202f2f2f2050617373657320616c6f6e672074686520627269646765207265717565737420746f20746865206465646963617465642062726964676520636f6e74726163742c2072657475726e696e67207468652062726964676564204e46540a20202020202020202f2f2f0a20202020202020202f2f2f2040706172616d2063616c6c65723a2041207265666572656e636520746f2074686520434f412077686963682063757272656e746c79206f776e732074686520746f6b656e7320696e2045564d0a20202020202020202f2f2f2040706172616d20747970653a2054686520436164656e63652074797065206f66207468652066756e6769626c6520746f6b656e207661756c7420746f20626520627269646765642066726f6d2045564d0a20202020202020202f2f2f2040706172616d20616d6f756e743a2054686520616d6f756e74206f6620746f6b656e7320746f20626520627269646765640a20202020202020202f2f2f2040706172616d2066656550726f76696465723a2041207265666572656e636520746f20612046756e6769626c65546f6b656e2050726f76696465722066726f6d20776869636820746865206272696467696e67206665652069732077697468647261776e20696e2024464c4f570a20202020202020202f2f2f0a20202020202020202f2f2f204072657475726e205468652062726964676564204e46540a20202020202020202f2f2f0a20202020202020206163636573732845564d2e427269646765290a202020202020202066756e207769746864726177546f6b656e73280a20202020202020202020202063616c6c65723a20617574682845564d2e43616c6c29202645564d2e436164656e63654f776e65644163636f756e742c0a202020202020202020202020747970653a20547970652c0a202020202020202020202020616d6f756e743a2055496e743235362c0a20202020202020202020202066656550726f76696465723a20617574682846756e6769626c65546f6b656e2e57697468647261772920267b46756e6769626c65546f6b656e2e50726f76696465727d0a2020202020202020293a20407b46756e6769626c65546f6b656e2e5661756c747d207b0a2020202020202020202020206c657420627269646765203d2073656c662e626f72726f7742726964676528290a2020202020202020202020202f2f20446566696e6520612063616c6c6261636b2066756e6374696f6e2c20656e61626c696e67207468652062726964676520746f20616374206f6e2074686520657068656d6572616c20434f41207265666572656e636520696e2073636f70650a202020202020202020202020766172206578656375746564203d2066616c73650a20202020202020202020202066756e2063616c6c6261636b28293a2045564d2e526573756c74207b0a20202020202020202020202020202020707265207b0a20202020202020202020202020202020202020202165786563757465643a202243616c6c6261636b2063616e206f6e6c79206265206578656375746564206f6e6365220a202020202020202020202020202020207d0a20202020202020202020202020202020706f7374207b0a202020202020202020202020202020202020202065786563757465643a202243616c6c6261636b206d757374206265206578656375746564220a202020202020202020202020202020207d0a202020202020202020202020202020206578656375746564203d20747275650a2020202020202020202020202020202072657475726e2063616c6c65722e63616c6c280a2020202020202020202020202020202020202020746f3a206272696467652e6765744173736f63696174656445564d4164647265737328776974683a2074797065290a2020202020202020202020202020202020202020202020203f3f2070616e696328224e6f2045564d2061646472657373206173736f6369617465642077697468207479706522292c0a2020202020202020202020202020202020202020646174613a2045564d2e656e636f6465414249576974685369676e6174757265280a202020202020202020202020202020202020202020202020227472616e7366657228616464726573732c75696e7432353629222c0a2020202020202020202020202020202020202020202020205b6272696467652e676574427269646765434f4145564d4164647265737328292c20616d6f756e745d0a2020202020202020202020202020202020202020292c0a20202020202020202020202020202020202020206761734c696d69743a2031353030303030302c0a202020202020202020202020202020202020202076616c75653a2045564d2e42616c616e6365286174746f666c6f773a2030290a20202020202020202020202020202020290a2020202020202020202020207d0a2020202020202020202020202f2f2045786563757465207468652062726964676520726571756573740a20202020202020202020202072657475726e203c2d206272696467652e627269646765546f6b656e7346726f6d45564d280a202020202020202020202020202020206f776e65723a2063616c6c65722e6164647265737328292c0a20202020202020202020202020202020747970653a20747970652c0a20202020202020202020202020202020616d6f756e743a20616d6f756e742c0a2020202020202020202020202020202066656550726f76696465723a2066656550726f76696465722c0a2020202020202020202020202020202070726f7465637465645472616e7366657243616c6c3a2063616c6c6261636b0a202020202020202020202020290a20202020202020207d0a0a20202020202020202f2f2f2053657473207468652062726964676520636f6e74726163742074686520726f75746572206469726563747320627269646765207265717565737473207468726f7567680a20202020202020202f2f2f0a202020202020202061636365737328526f7574657241646d696e292066756e20736574427269646765436f6e747261637428616464726573733a20416464726573732c206e616d653a20537472696e6729207b0a20202020202020202020202073656c662e62726964676541646472657373203d20616464726573730a20202020202020202020202073656c662e627269646765436f6e74726163744e616d65203d206e616d650a202020202020202020202020656d697420427269646765436f6e74726163745570646174656428616464726573733a20616464726573732c206e616d653a206e616d65290a20202020202020207d0a0a20202020202020202f2f2f2052657475726e732061207265666572656e636520746f207468652062726964676520636f6e74726163740a20202020202020202f2f2f0a20202020202020206163636573732873656c66292066756e20626f72726f7742726964676528293a20267b49466c6f7745564d4e46544272696467652c2049466c6f7745564d546f6b656e4272696467657d207b0a20202020202020202020202072657475726e206765744163636f756e742873656c662e62726964676541646472657373292e636f6e7472616374732e626f72726f773c267b49466c6f7745564d4e46544272696467652c2049466c6f7745564d546f6b656e4272696467657d3e280a20202020202020202020202020202020202020206e616d653a2073656c662e627269646765436f6e74726163744e616d650a2020202020202020202020202020202029203f3f2070616e6963282242726964676520636f6e7472616374206e6f7420666f756e6422290a20202020202020207d0a202020207d0a0a20202020696e697428627269646765416464726573733a20416464726573732c20627269646765436f6e74726163744e616d653a20537472696e6729207b0a202020202020202073656c662e6163636f756e742e73746f726167652e73617665280a2020202020202020202020203c2d63726561746520526f7574657228616464726573733a20627269646765416464726573732c206e616d653a20627269646765436f6e74726163744e616d65292c0a202020202020202020202020746f3a202f73746f726167652f65766d427269646765526f757465720a2020202020202020290a202020207d0a7d0a" +access(all) let compiledWFLOWBytecode = "60c0604052600c60808190526b5772617070656420466c6f7760a01b60a090815261002d916000919061007a565b506040805180820190915260058082526457464c4f5760d81b602090920191825261005a9160019161007a565b506002805460ff1916601217905534801561007457600080fd5b50610115565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100bb57805160ff19168380011785556100e8565b828001600101855582156100e8579182015b828111156100e85782518255916020019190600101906100cd565b506100f49291506100f8565b5090565b61011291905b808211156100f457600081556001016100fe565b90565b6106e3806101246000396000f3fe60806040526004361061009c5760003560e01c8063313ce56711610064578063313ce5671461021157806370a082311461023c57806395d89b411461026f578063a9059cbb14610284578063d0e30db01461009c578063dd62ed3e146102bd5761009c565b806306fdde03146100a6578063095ea7b31461013057806318160ddd1461017d57806323b872dd146101a45780632e1a7d4d146101e7575b6100a46102f8565b005b3480156100b257600080fd5b506100bb610347565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f55781810151838201526020016100dd565b50505050905090810190601f1680156101225780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561013c57600080fd5b506101696004803603604081101561015357600080fd5b506001600160a01b0381351690602001356103d5565b604080519115158252519081900360200190f35b34801561018957600080fd5b5061019261043b565b60408051918252519081900360200190f35b3480156101b057600080fd5b50610169600480360360608110156101c757600080fd5b506001600160a01b0381358116916020810135909116906040013561043f565b3480156101f357600080fd5b506100a46004803603602081101561020a57600080fd5b5035610573565b34801561021d57600080fd5b50610226610608565b6040805160ff9092168252519081900360200190f35b34801561024857600080fd5b506101926004803603602081101561025f57600080fd5b50356001600160a01b0316610611565b34801561027b57600080fd5b506100bb610623565b34801561029057600080fd5b50610169600480360360408110156102a757600080fd5b506001600160a01b03813516906020013561067d565b3480156102c957600080fd5b50610192600480360360408110156102e057600080fd5b506001600160a01b0381358116916020013516610691565b33600081815260036020908152604091829020805434908101909155825190815291517fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c9281900390910190a2565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103cd5780601f106103a2576101008083540402835291602001916103cd565b820191906000526020600020905b8154815290600101906020018083116103b057829003601f168201915b505050505081565b3360008181526004602090815260408083206001600160a01b038716808552908352818420869055815186815291519394909390927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925928290030190a350600192915050565b4790565b6001600160a01b03831660009081526003602052604081205482111561046457600080fd5b6001600160a01b03841633148015906104a257506001600160a01b038416600090815260046020908152604080832033845290915290205460001914155b15610502576001600160a01b03841660009081526004602090815260408083203384529091529020548211156104d757600080fd5b6001600160a01b03841660009081526004602090815260408083203384529091529020805483900390555b6001600160a01b03808516600081815260036020908152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060019392505050565b3360009081526003602052604090205481111561058f57600080fd5b33600081815260036020526040808220805485900390555183156108fc0291849190818181858888f193505050501580156105ce573d6000803e3d6000fd5b5060408051828152905133917f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65919081900360200190a250565b60025460ff1681565b60036020526000908152604090205481565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103cd5780601f106103a2576101008083540402835291602001916103cd565b600061068a33848461043f565b9392505050565b60046020908152600092835260408084209091529082529020548156fea265627a7a7231582070f4b62cd9290b18cc1aa556d5b98fd34e7976b42cbe1a04c5553cc18b2b915c64736f6c63430005110032" + access(all) let bridgedNFTCodeChunks = [ "696d706f7274204e6f6e46756e6769626c65546f6b656e2066726f6d203078303030303030303030303030303030310a696d706f7274204d6574616461746156696577732066726f6d203078303030303030303030303030303030310a696d706f727420566965775265736f6c7665722066726f6d203078303030303030303030303030303030310a696d706f72742046756e6769626c65546f6b656e2066726f6d203078303030303030303030303030303030320a696d706f727420466c6f77546f6b656e2066726f6d203078303030303030303030303030303030330a0a696d706f72742045564d2066726f6d203078303030303030303030303030303030310a0a696d706f7274204943726f7373564d2066726f6d203078303030303030303030303030303030370a696d706f7274204943726f7373564d41737365742066726f6d203078303030303030303030303030303030370a696d706f7274204945564d4272696467654e46544d696e7465722066726f6d203078303030303030303030303030303030370a696d706f727420466c6f7745564d4272696467654e4654457363726f772066726f6d203078303030303030303030303030303030370a696d706f727420466c6f7745564d427269646765436f6e6669672066726f6d203078303030303030303030303030303030370a696d706f727420466c6f7745564d4272696467655574696c732066726f6d203078303030303030303030303030303030370a696d706f727420466c6f7745564d4272696467652066726f6d203078303030303030303030303030303030370a696d706f72742043726f7373564d4e46542066726f6d203078303030303030303030303030303030370a696d706f727420466c6f7745564d4272696467655265736f6c7665722066726f6d203078303030303030303030303030303030370a0a2f2f2f205468697320636f6e747261637420697320612074656d706c617465207573656420627920466c6f7745564d42726964676520746f20646566696e652045564d2d6e6174697665204e46547320627269646765642066726f6d20466c6f772045564d20746f20466c6f772e0a2f2f2f2055706f6e206465706c6f796d656e74206f66207468697320636f6e74726163742c2074686520636f6e7472616374206e616d65206973206465726976656420617320612066756e6374696f6e206f6620746865206173736574207479706520286865726520616e2045524337323120616b610a2f2f2f20616e204e46542920616e642074686520636f6e747261637427732045564d20616464726573732e20546865206465726976656420636f6e7472616374206e616d65206973207468656e206a6f696e65642077697468207468697320636f6e7472616374277320636f64652c0a2f2f2f207072657061726564206173206368756e6b7320696e20466c6f7745564d42726964676554656d706c61746573206265666f7265206265696e67206465706c6f79656420746f2074686520466c6f772045564d20427269646765206163636f756e742e0a2f2f2f0a2f2f2f204f6e206272696467696e672c2074686520455243373231206973207472616e7366657272656420746f2074686520627269646765277320436164656e63654f776e65644163636f756e742045564d206164647265737320616e642061206e6577204e4654206973206d696e7465642066726f6d0a2f2f2f207468697320636f6e747261637420746f20746865206272696467696e672063616c6c65722e204f6e2072657475726e20746f20466c6f772045564d2c2074686520726576657273652070726f6365737320697320666f6c6c6f776564202d2074686520746f6b656e206973206c6f636b65640a2f2f2f20696e204e465420657363726f7720616e642074686520455243373231206973207472616e7366657272656420746f2074686520646566696e656420726563697069656e742e20496e2074686973207761792c2074686520436164656e636520746f6b656e206163747320617320610a2f2f2f20726570726573656e746174696f6e206f6620626f7468207468652045564d204e465420616e642074687573206f776e6572736869702072696768747320746f2069742075706f6e206272696467696e67206261636b20746f20466c6f772045564d2e0a2f2f2f0a2f2f2f20546f20627269646765206265747765656e20564d732c20612063616c6c65722063616e20656974686572207573652074686520696e74657266616365206578706f736564206f6e20436164656e63654f776e65644163636f756e74206f722075736520466c6f7745564d4272696467650a2f2f2f207075626c696320636f6e7472616374206d6574686f64732e0a2f2f2f0a61636365737328616c6c2920636f6e747261637420", "203a204943726f7373564d2c204943726f7373564d41737365742c204945564d4272696467654e46544d696e7465722c204e6f6e46756e6769626c65546f6b656e207b0a0a202020202f2f2f20506f696e74657220746f2074686520466163746f7279206465706c6f79656420536f6c696469747920636f6e7472616374206164647265737320646566696e696e672074686520627269646765642061737365740a2020202061636365737328616c6c29206c65742065766d4e4654436f6e7472616374416464726573733a2045564d2e45564d416464726573730a202020202f2f2f204e616d65206f6620746865204e465420636f6c6c656374696f6e20646566696e656420696e2074686520636f72726573706f6e64696e672045524337323120636f6e74726163740a2020202061636365737328616c6c29206c6574206e616d653a20537472696e670a202020202f2f2f2053796d626f6c206f6620746865204e465420636f6c6c656374696f6e20646566696e656420696e2074686520636f72726573706f6e64696e672045524337323120636f6e74726163740a2020202061636365737328616c6c29206c65742073796d626f6c3a20537472696e670a202020202f2f2f20555249206f662074686520636f6e74726163742c20696620617661696c61626c6520617320612076617220696e2063617365207468652062726964676520656e61626c65732063726f73732d564d204d657461646174612073796e63696e6720696e20746865206675747572650a2020202061636365737328616c6c292076617220636f6e74726163745552493a20537472696e673f0a202020202f2f2f2052657461696e206120436f6c6c656374696f6e20746f207265666572656e6365207768656e207265736f6c76696e6720436f6c6c656374696f6e204d657461646174610a202020206163636573732873656c6629206c657420636f6c6c656374696f6e3a2040436f6c6c656374696f6e0a202020202f2f2f204d617070696e67206f6620746f6b656e205552497320696e6465786564206f6e207468656972204552433732312049442e205468697320776f756c64206e6f74206e6f726d616c6c792062652072657461696e65642077697468696e206120436164656e6365204e46540a202020202f2f2f20636f6e74726163742c206275742073696e6365204e4654206d65746164617461206d6179206265207570646174656420696e2045564d2c20697427732072657461696e6564206865726520736f207468617420746865206272696467652063616e207570646174650a202020202f2f2f20697420616761696e73742074686520736f757263652045524337323120636f6e7472616374207768696368206973207472656174656420617320746865204e4654277320736f75726365206f662074727574682e0a2020202061636365737328616c6c29206c657420746f6b656e555249733a207b55496e743235363a20537472696e677d0a0a202020202f2f2f20546865204e4654207265736f7572636520726570726573656e74696e672074686520627269646765642045524337323120746f6b656e0a202020202f2f2f0a2020202061636365737328616c6c29207265736f75726365204e4654203a204943726f7373564d41737365742e4173736574496e666f2c2043726f7373564d4e46542e45564d4e4654207b0a20202020202020202f2f2f2054686520436164656e6365204944206f6620746865204e46540a202020202020202061636365737328616c6c29206c65742069643a2055496e7436340a20202020202020202f2f2f2054686520455243373231204944206f6620746865204e46540a202020202020202061636365737328616c6c29206c65742065766d49443a2055496e743235360a20202020202020202f2f2f204164646974696f6e616c206f6e636861696e206d657461646174610a202020202020202061636365737328616c6c29206c6574206d657461646174613a207b537472696e673a20416e795374727563747d0a0a2020202020202020696e6974280a20202020202020202020202065766d49443a2055496e743235362c0a2020202020202020202020206d657461646174613a207b537472696e673a20416e795374727563747d0a202020202020202029207b0a20202020202020202020202073656c662e6964203d2073656c662e757569640a20202020202020202020202073656c662e65766d4944203d2065766d49440a20202020202020202020202073656c662e6d65746164617461203d206d657461646174610a20202020202020207d0a0a20202020202020202f2f2f2052657475726e7320746865206d65746164617461207669657720747970657320737570706f727465642062792074686973204e46540a202020202020202061636365737328616c6c2920766965772066756e20676574566965777328293a205b547970655d207b0a20202020202020202020202072657475726e205b0a20202020202020202020202020202020547970653c4d6574616461746156696577732e446973706c61793e28292c0a20202020202020202020202020202020547970653c4d6574616461746156696577732e53657269616c3e28292c0a20202020202020202020202020202020547970653c4d6574616461746156696577732e4e4654436f6c6c656374696f6e446174613e28292c0a20202020202020202020202020202020547970653c4d6574616461746156696577732e4e4654436f6c6c656374696f6e446973706c61793e28292c0a20202020202020202020202020202020547970653c4d6574616461746156696577732e45564d427269646765644d657461646174613e28290a2020202020202020202020205d0a20202020202020207d0a0a202020202020202061636365737328616c6c2920766965772066756e206765744e616d6528293a20537472696e67207b0a20202020202020202020202072657475726e20", @@ -110,6 +112,11 @@ fun getCompiledERC20Bytecode(): String { return compiledERC20Bytecode } +access(all) +fun getCompiledWFLOWBytecode(): String { + return compiledWFLOWBytecode +} + access(all) fun getEVMBridgeRouterCode(): String { return evmBridgeRouterCode From a506223a634173f2443bc1ee76c51e94d97efbee Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Wed, 18 Sep 2024 17:44:19 -0600 Subject: [PATCH 04/13] fix FlowEVMBridgeUtils.borrowCOA() --- cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc | 4 ++-- cadence/contracts/bridge/FlowEVMBridgeUtils.cdc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index 93d760a5..635d706f 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -333,7 +333,7 @@ access(all) contract FlowEVMBridgeHandlers { let unwrapResult = FlowEVMBridgeUtils.call( signature: "withdraw(uint)", targetEVMAddress: wflowAddress, - args: [UInt(amount)], + args: [amount], gasLimit: FlowEVMBridgeConfig.gasLimit, value: 0.0 ) @@ -344,7 +344,7 @@ access(all) contract FlowEVMBridgeHandlers { // Cover underflow assert( postBalance > preBalance, - message: "Balance decremented after unwrapping WFLOW" + message: "Balance did not increment after unwrapping WFLOW amount=".concat(amount.toString()) ) // Confirm bridge COA's FLOW balance has incremented by the expected amount assert( diff --git a/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc b/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc index e5e35ad6..b1295ff1 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeUtils.cdc @@ -1040,7 +1040,7 @@ contract FlowEVMBridgeUtils { /// access(account) view fun borrowCOA(): auth(EVM.Call, EVM.Withdraw) &EVM.CadenceOwnedAccount { - return self.account.storage.borrow( + return self.account.storage.borrow( from: FlowEVMBridgeConfig.coaStoragePath ) ?? panic("Could not borrow COA reference") } From 53ce62fb6d3150b66d64d4ffe76aa1811d83ea47 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Thu, 19 Sep 2024 10:05:07 -0600 Subject: [PATCH 05/13] add initial WFLOW handler tests --- .../tests/flow_evm_wflow_handler_tests.cdc | 557 +++++++++++++ .../create_wflow_token_handler.cdc | 32 + .../example-assets/evm-assets/unwrap_flow.cdc | 50 ++ .../example-assets/evm-assets/wrap_flow.cdc | 42 + solidity/src/handled-assets/WETH9.sol | 756 ++++++++++++++++++ 5 files changed, 1437 insertions(+) create mode 100644 cadence/tests/flow_evm_wflow_handler_tests.cdc create mode 100644 cadence/transactions/bridge/admin/token-handler/create_wflow_token_handler.cdc create mode 100644 cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc create mode 100644 cadence/transactions/example-assets/evm-assets/wrap_flow.cdc create mode 100644 solidity/src/handled-assets/WETH9.sol diff --git a/cadence/tests/flow_evm_wflow_handler_tests.cdc b/cadence/tests/flow_evm_wflow_handler_tests.cdc new file mode 100644 index 00000000..a89013d7 --- /dev/null +++ b/cadence/tests/flow_evm_wflow_handler_tests.cdc @@ -0,0 +1,557 @@ +import Test +import BlockchainHelpers + +import "FungibleToken" +import "NonFungibleToken" +import "FlowStorageFees" +import "EVM" + +import "test_helpers.cdc" + +access(all) let serviceAccount = Test.serviceAccount() +access(all) let bridgeAccount = Test.getAccount(0x0000000000000007) +access(all) let exampleERCAccount = Test.getAccount(0x0000000000000009) +access(all) let alice = Test.createAccount() +access(all) var aliceCOAAddressHex: String = "" + +// FlowToken +access(all) let flowTokenAccountAddress = Address(0x0000000000000003) +access(all) let flowTokenIdentifier = "A.0000000000000003.FlowToken.Vault" +access(all) let flowFundingAmount = 201.0 +access(all) let coaFundingAmount = 100.0 + +// WFLOW values +access(all) var wflowAddressHex: String = "" +access(all) let erc20MintAmount: UInt256 = 100_000_000_000_000_000_000 +access(all) let wrapFlowAmount: UFix64 = 100.0 + +// Fee initialiazation values +access(all) let expectedOnboardFee = 1.0 +access(all) let expectedBaseFee = 0.001 + +// Default decimals for Cadence UFix64 values +access(all) let defaultDecimals: UInt8 = 18 + +// Test height snapshot for test state resets +access(all) var snapshot: UInt64 = 0 + +access(all) +fun setup() { + // Deploy supporting util contracts + var err = Test.deployContract( + name: "ArrayUtils", + path: "../contracts/utils/ArrayUtils.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "StringUtils", + path: "../contracts/utils/StringUtils.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "ScopedFTProviders", + path: "../contracts/utils/ScopedFTProviders.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "Serialize", + path: "../contracts/utils/Serialize.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "SerializeMetadata", + path: "../contracts/utils/SerializeMetadata.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + // Transfer bridge account some $FLOW + transferFlow(signer: serviceAccount, recipient: bridgeAccount.address, amount: 10_000.0) + // Configure bridge account with a COA + createCOA(signer: bridgeAccount, fundingAmount: 1_000.0) + + err = Test.deployContract( + name: "IBridgePermissions", + path: "../contracts/bridge/interfaces/IBridgePermissions.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "ICrossVM", + path: "../contracts/bridge/interfaces/ICrossVM.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "ICrossVMAsset", + path: "../contracts/bridge/interfaces/ICrossVMAsset.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "CrossVMNFT", + path: "../contracts/bridge/interfaces/CrossVMNFT.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "CrossVMToken", + path: "../contracts/bridge/interfaces/CrossVMToken.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeHandlerInterfaces", + path: "../contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeConfig", + path: "../contracts/bridge/FlowEVMBridgeConfig.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + // Deploy FlowBridgeFactory.sol + let deploymentResult = executeTransaction( + "../transactions/evm/deploy.cdc", + [getCompiledFactoryBytecode(), 15_000_000, 0.0], + bridgeAccount + ) + // Get the deployed contract address from the latest EVM event + let evts = Test.eventsOfType(Type()) + Test.assertEqual(2, evts.length) + let factoryAddressHex = getEVMAddressHexFromEvents(evts, idx: 0) + + err = Test.deployContract( + name: "FlowEVMBridgeUtils", + path: "../contracts/bridge/FlowEVMBridgeUtils.cdc", + arguments: [factoryAddressHex] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeResolver", + path: "../contracts/bridge/FlowEVMBridgeResolver.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeNFTEscrow", + path: "../contracts/bridge/FlowEVMBridgeNFTEscrow.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeTokenEscrow", + path: "../contracts/bridge/FlowEVMBridgeTokenEscrow.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeTemplates", + path: "../contracts/bridge/FlowEVMBridgeTemplates.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + // Commit bridged NFT code + let bridgedNFTChunkResult = executeTransaction( + "../transactions/bridge/admin/templates/upsert_contract_code_chunks.cdc", + ["bridgedNFT", getBridgedNFTCodeChunks()], + bridgeAccount + ) + Test.expect(bridgedNFTChunkResult, Test.beSucceeded()) + // Commit bridged Token code + let bridgedTokenChunkResult = executeTransaction( + "../transactions/bridge/admin/templates/upsert_contract_code_chunks.cdc", + ["bridgedToken", getBridgedTokenCodeChunks()], + bridgeAccount + ) + Test.expect(bridgedNFTChunkResult, Test.beSucceeded()) + + err = Test.deployContract( + name: "IEVMBridgeNFTMinter", + path: "../contracts/bridge/interfaces/IEVMBridgeNFTMinter.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "IEVMBridgeTokenMinter", + path: "../contracts/bridge/interfaces/IEVMBridgeTokenMinter.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "IFlowEVMNFTBridge", + path: "../contracts/bridge/interfaces/IFlowEVMNFTBridge.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "IFlowEVMTokenBridge", + path: "../contracts/bridge/interfaces/IFlowEVMTokenBridge.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridge", + path: "../contracts/bridge/FlowEVMBridge.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + err = Test.deployContract( + name: "FlowEVMBridgeAccessor", + path: "../contracts/bridge/FlowEVMBridgeAccessor.cdc", + arguments: [serviceAccount.address] + ) + Test.expect(err, Test.beNil()) + + let claimAccessorResult = executeTransaction( + "../transactions/bridge/admin/evm-integration/claim_accessor_capability_and_save_router.cdc", + ["FlowEVMBridgeAccessor", bridgeAccount.address], + serviceAccount + ) + Test.expect(claimAccessorResult, Test.beSucceeded()) + + err = Test.deployContract( + name: "FlowEVMBridgeHandlers", + path: "../contracts/bridge/FlowEVMBridgeHandlers.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + // Set bridge fees + let updateOnboardFeeResult = executeTransaction( + "../transactions/bridge/admin/fee/update_onboard_fee.cdc", + [expectedOnboardFee], + bridgeAccount + ) + Test.expect(updateOnboardFeeResult, Test.beSucceeded()) + let updateBaseFeeResult = executeTransaction( + "../transactions/bridge/admin/fee/update_base_fee.cdc", + [expectedBaseFee], + bridgeAccount + ) + Test.expect(updateBaseFeeResult, Test.beSucceeded()) + + // Unpause Bridge + updateBridgePauseStatus(signer: bridgeAccount, pause: false) +} + +/* --- ASSET & ACCOUNT SETUP - Configure test accounts with assets to bridge --- */ + +// Create a COA in Alice's account who will be the test asset owner for both Cadence & ERC20 FTs +access(all) +fun testCreateCOASucceeds() { + // Alice's account gets 201.0 FLOW + transferFlow(signer: serviceAccount, recipient: alice.address, amount: flowFundingAmount) + // Fund the COA with 100.0 FLOW of the 201.0 FLOW in Alice's account + createCOA(signer: alice, fundingAmount: coaFundingAmount) + + aliceCOAAddressHex = getCOAAddressHex(atFlowAddress: alice.address) +} + +// WFLOW deploys successfully - this will be used as the targetEVMAddress in our TokenHandler +access(all) +fun testDeployWFLOWSucceeds() { + // Anyone can deploy WFLOW as its unowned - we just use any account here to deploy + let wflowDeployResult = executeTransaction( + "../transactions/evm/deploy.cdc", + [getCompiledWFLOWBytecode(), UInt64(15_000_000), 0.0], + alice + ) + Test.expect(wflowDeployResult, Test.beSucceeded()) + + let evts = Test.eventsOfType(Type()) + Test.assertEqual(5, evts.length) + wflowAddressHex = getEVMAddressHexFromEvents(evts, idx: 4) + log("WFLOW Address: ".concat(wflowAddressHex)) +} + +access(all) +fun testWrapFLOWSucceeds() { + let wrapResult = executeTransaction( + "../transactions/example-assets/evm-assets/wrap_flow.cdc", + [wflowAddressHex, coaFundingAmount], + alice + ) + Test.expect(wrapResult, Test.beSucceeded()) + + // Validate that the wrapping was successful by getting alice's COA's WFLOW balance + let wflowBalance = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) + + // Get WFLOW total supply + let wflowTotalSupply = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + let coaFundingAmountUInt = ufix64ToUInt256(coaFundingAmount, decimals: defaultDecimals) + Test.assertEqual(coaFundingAmountUInt, wflowBalance) +} + +// Configuring the Handler also disables onboarding of WFLOW to the bridge +access(all) +fun testCreateWFLOWTokenHandlerSucceeds() { + // Create TokenHandler for WFLOW, specifying the target type and expected minter type + let createHandlerResult = executeTransaction( + "../transactions/bridge/admin/token-handler/create_wflow_token_handler.cdc", + [wflowAddressHex], + bridgeAccount + ) + Test.expect(createHandlerResult, Test.beSucceeded()) + + // TODO: Add event validation when EVM and EVM dependent contracts can be imported to Test env +} + +// /* --- ONBOARDING - Test asset onboarding to the bridge --- */ + +// Since the type has a TokenHandler, onboarding should fail +access(all) +fun testOnboardFlowTokenByTypeFails() { + var onboaringRequiredResult = executeScript( + "../scripts/bridge/type_requires_onboarding_by_identifier.cdc", + [flowTokenIdentifier] + ) + Test.expect(onboaringRequiredResult, Test.beSucceeded()) + var requiresOnboarding = onboaringRequiredResult.returnValue as! Bool? ?? panic("Problem getting onboarding requirement") + Test.assertEqual(false, requiresOnboarding) + + // Should fail since request routes to TokenHandler and it's not enabled + let onboardingResult = executeTransaction( + "../transactions/bridge/onboarding/onboard_by_type_identifier.cdc", + [flowTokenIdentifier], + alice + ) + Test.expect(onboardingResult, Test.beFailed()) +} + +// Since the WFLOW Address has a TokenHandler, onboarding should fail +access(all) +fun testOnboardWFLOWByEVMAddressFails() { + + var onboaringRequiredResult = executeScript( + "../scripts/bridge/evm_address_requires_onboarding.cdc", + [wflowAddressHex] + ) + Test.expect(onboaringRequiredResult, Test.beSucceeded()) + var requiresOnboarding = onboaringRequiredResult.returnValue as! Bool? ?? panic("Problem getting onboarding requirement") + Test.assertEqual(false, requiresOnboarding) + + // Should fails since request routes to TokenHandler and it's not enabled + var onboardingResult = executeTransaction( + "../transactions/bridge/onboarding/onboard_by_evm_address.cdc", + [wflowAddressHex], + alice + ) + Test.expect(onboardingResult, Test.beFailed()) +} + +/* --- BRIDGING FUNGIBLE TOKENS - Test bridging both Cadence- & EVM-native fungible tokens --- */ + +// Now enable TokenHandler to bridge in both directions +access(all) +fun testEnableWFLOWTokenHandlerSucceeds() { + let enabledResult = executeTransaction( + "../transactions/bridge/admin/token-handler/enable_token_handler.cdc", + [flowTokenIdentifier], + bridgeAccount + ) + Test.expect(enabledResult, Test.beSucceeded()) + // TODO: Validate event emission and values +} + +// Validate that funds can be bridged from Cadence to EVM, resulting in balance increase in WFLOW as target +access(all) +fun testBridgeFLOWTokenToEVMFirstSucceeds() { + snapshot = getCurrentBlockHeight() + + // Take note of the total supply before bridging + let wflowTotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + + var cadenceBalance = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") + ?? panic("Problem getting FlowToken balance") + Test.assert(cadenceBalance == flowFundingAmount - coaFundingAmount, message: "Invalid Cadence balance") + let remainder = 1.0 + let bridgeAmount = cadenceBalance - remainder + + // Convert the bridge amount to UInt256 for EVM balance comparison + let coaFundingAmountUInt = ufix64ToUInt256(coaFundingAmount, decimals: defaultDecimals) + let uintBridgeAmount = ufix64ToUInt256(bridgeAmount, decimals: defaultDecimals) + + // Execute bridge to EVM + bridgeTokensToEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: flowTokenAccountAddress, + contractName: "FlowToken", + resourceName: "Vault" + ), + amount: bridgeAmount, + beFailed: false + ) + + // Confirm ownership on EVM side with Alice COA as owner of bridged WFLOW + let evmBalance = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) + Test.assertEqual(coaFundingAmountUInt + uintBridgeAmount, evmBalance) // bridged balance + previously minted ERC20 + + // Validate that the WFLOW balance in circulation increased by the amount bridged + let wflowTotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + Test.assertEqual(wflowTotalSupplyBefore, wflowTotalSupplyAfter - uintBridgeAmount) + + // Ensure that Alice's WFLOW balance is the sum of the minted amount and the amount bridged + let aliceEVMBalance = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) + Test.assertEqual(coaFundingAmountUInt + uintBridgeAmount, aliceEVMBalance) +} + +// With all funds now in EVM, we can test bridging back to Cadence +access(all) +fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { + + let wflowTotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + + let cadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") + ?? panic("Problem getting FlowToken balance") + + // Execute bridge from EVM, bridging Alice's full balance to Cadence + let wflowBalanceBefore = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) + let ufixEVMbalance = uint256ToUFix64(wflowBalanceBefore, decimals: defaultDecimals) + bridgeTokensFromEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: flowTokenAccountAddress, + contractName: "FlowToken", + resourceName: "Vault" + ), + amount: wflowBalanceBefore, + beFailed: false + ) + + // Confirm that Alice's balance has been bridged to Cadence + let cadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") + ?? panic("Problem getting FlowToken balance") + Test.assertEqual(ufixEVMbalance, cadenceBalanceAfter) + + // Confirm that the ERC20 balance was burned in the process of bridging + let evmBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) + Test.assertEqual(UInt256(0), evmBalanceAfter) + + // // Validate that the ERC20 balance in circulation remained the same + // let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + // Test.assertEqual(wflowTotalSupplyBefore, erc20TotalSupplyAfter) + + // // Validate that all ERC20 funds are now in escrow since all bridged to Cadence + // let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) + // Test.assertEqual(erc20TotalSupplyAfter, escrowBalance) +} + +// // Now test bridging with liquidity flow moving entirely from EVM to Cadence and back +// access(all) +// fun testBridgeWFLOWTokenFromEVMFirstSucceeds() { +// // Reset to snapshot before bridging between VMs +// Test.reset(to: snapshot) + + +// var erc20TotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) +// let cadenceTotalSupplyBefore = getCadenceTotalSupply( +// contractAddress: flowTokenAccountAddress, +// contractName: "FlowToken", +// vaultIdentifier: flowTokenIdentifier +// ) ?? panic("Problem getting total supply of Cadence tokens") +// let uintCadenceTotalSupplyBefore = ufix64ToUInt256(cadenceTotalSupplyBefore, decimals: defaultDecimals) +// Test.assertEqual(uintCadenceTotalSupplyBefore + erc20MintAmount, erc20TotalSupplyBefore) + +// // Alice should start with amount previously minted +// let aliceEVMBalanceBefore = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) +// Test.assertEqual(erc20MintAmount, aliceEVMBalanceBefore) +// // Cadence total supply should match the amount in escrow +// let escrowBalanceBefore = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) +// Test.assertEqual(uintCadenceTotalSupplyBefore, escrowBalanceBefore) + +// // Alice was the only one minted Cadence tokens, so should have the total supply in Cadence +// let aliceCadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") +// ?? panic("Problem getting FlowToken balance") +// Test.assertEqual(flowTokenMintAmount, aliceCadenceBalanceBefore) +// Test.assertEqual(cadenceTotalSupplyBefore, aliceCadenceBalanceBefore) + +// // Convert the bridge amount to UFix64 for Cadence balance comparison +// let ufixBridgeAmount = uint256ToUFix64(erc20MintAmount, decimals: defaultDecimals) + +// // Execute bridge from EVM +// bridgeTokensFromEVM( +// signer: alice, +// vaultIdentifier: buildTypeIdentifier( +// address: flowTokenAccountAddress, +// contractName: "FlowToken", +// resourceName: "Vault" +// ), +// amount: aliceEVMBalanceBefore, +// beFailed: false +// ) + +// // Confirm that Alice's balance is now the total supply, having incremented by the amount bridged into Cadence +// let aliceCadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") +// ?? panic("Problem getting FlowToken balance") +// let cadenceTotalSupplyAfter = getCadenceTotalSupply( +// contractAddress: flowTokenAccountAddress, +// contractName: "FlowToken", +// vaultIdentifier: flowTokenIdentifier +// ) ?? panic("Problem getting total supply of Cadence tokens") +// Test.assertEqual(cadenceTotalSupplyAfter, aliceCadenceBalanceAfter) +// Test.assertEqual(cadenceTotalSupplyAfter, cadenceTotalSupplyBefore + ufixBridgeAmount) + +// // Confirm Alice's EVM balance is now 0 +// let aliceEVMBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) +// Test.assertEqual(UInt256(0), aliceEVMBalanceAfter) + +// // Confirm that the amount in escrow incremented +// let escrowBalanceAfter = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) +// Test.assertEqual(escrowBalanceBefore + aliceEVMBalanceBefore, escrowBalanceAfter) + +// // Ensure the ERC20 balance in circulation remained the same +// let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) +// Test.assertEqual(erc20TotalSupplyBefore, erc20TotalSupplyAfter) +// } + +// // Now return all liquidity back to EVM +// access(all) +// fun testBridgeFLOWTokenToEVMSecondSucceeds() { + +// let erc20TotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + +// // Alice should start with amount previously minted +// let aliceEVMBalanceBefore = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) +// Test.assertEqual(UInt256(0), aliceEVMBalanceBefore) +// let aliceCadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") +// ?? panic("Problem getting FlowToken balance") + +// // Convert the bridge amount to UInt256 for EVM balance comparison +// let uintBridgeAmount = ufix64ToUInt256(aliceCadenceBalanceBefore, decimals: defaultDecimals) + +// // Execute bridge to EVM +// bridgeTokensToEVM( +// signer: alice, +// vaultIdentifier: buildTypeIdentifier( +// address: flowTokenAccountAddress, +// contractName: "FlowToken", +// resourceName: "Vault" +// ), amount: aliceCadenceBalanceBefore, +// beFailed: false +// ) + +// let aliceCadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") +// ?? panic("Problem getting FlowToken balance") +// Test.assertEqual(0.0, aliceCadenceBalanceAfter) + +// // Confirm ownership on EVM side with Alice COA as owner of ERC721 representation +// let aliceEVMBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) +// Test.assertEqual(uintBridgeAmount, aliceEVMBalanceAfter) + +// // Confirm that the ERC20 balance in circulation remained the same +// let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) +// Test.assertEqual(erc20TotalSupplyBefore, erc20TotalSupplyAfter) + +// // Confirm escrow balance is now 0 +// let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) +// Test.assertEqual(UInt256(0), escrowBalance) +// } diff --git a/cadence/transactions/bridge/admin/token-handler/create_wflow_token_handler.cdc b/cadence/transactions/bridge/admin/token-handler/create_wflow_token_handler.cdc new file mode 100644 index 00000000..495bb7a6 --- /dev/null +++ b/cadence/transactions/bridge/admin/token-handler/create_wflow_token_handler.cdc @@ -0,0 +1,32 @@ +import "FlowToken" + +import "EVM" + +import "FlowEVMBridgeHandlerInterfaces" +import "FlowEVMBridgeHandlers" + +/// Creates a WFLOWTokenHandler for moving FLOW between VMs. The TokenHandler is configured in the bridge to handle the +/// FlowToken Vault type. +/// +/// @param wflowEVMAddressHex: The EVM address of the WFLOW contract as a hex string +/// +transaction(wflowEVMAddressHex: String) { + + let configurator: auth(FlowEVMBridgeHandlerInterfaces.Admin) &FlowEVMBridgeHandlers.HandlerConfigurator + + prepare(signer: auth(BorrowValue, LoadValue) &Account) { + self.configurator = signer.storage.borrow( + from: FlowEVMBridgeHandlers.ConfiguratorStoragePath + ) ?? panic("Missing configurator") + } + + execute { + let wflowEVMAddress = EVM.addressFromString(wflowEVMAddressHex) + self.configurator.createTokenHandler( + handlerType: Type<@FlowEVMBridgeHandlers.WFLOWTokenHandler>(), + targetType: Type<@FlowToken.Vault>(), + targetEVMAddress: wflowEVMAddress, + expectedMinterType: nil + ) + } +} diff --git a/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc b/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc new file mode 100644 index 00000000..a31d85c3 --- /dev/null +++ b/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc @@ -0,0 +1,50 @@ +import "FungibleToken" +import "FlowToken" + +import "EVM" + +import "FlowEVMBridgeUtils" + +/// This transactions wraps FLOW tokens as WFLOW tokens, using the signing COA's EVM FLOW balance primarily. If the +/// EVM balance is insufficient, the transaction will transfer FLOW from the Cadence balance to the EVM balance. +/// +/// @param wflowContractHex: The EVM address of the WFLOW contract as a hex string +/// @param amount: The amount of FLOW to wrap as WFLOW +/// +transaction(wflowContractHex: String, amount: UInt256) { + + let wflowAddress: EVM.EVMAddress + let preBalance: UInt + let coa: auth(EVM.Call) &EVM.CadenceOwnedAccount + var postBalance: UInt + + prepare(signer: auth(BorrowValue) &Account) { + self.wflowAddress = EVM.addressFromString(wflowContractHex) + self.coa = signer.storage.borrow(from: /storage/evm) + ?? panic("Could not borrow COA from provided gateway address") + self.preBalance = UInt(FlowEVMBridgeUtils.balanceOf(owner: self.coa.address(), evmContractAddress: self.wflowAddress)) + self.postBalance = 0 + } + + execute { + // Encode the withdraw function call + let calldata = EVM.encodeABIWithSignature("withdraw(uint)", [UInt(amount)]) + // Define the value to send to the WFLOW contract - 0 to unwrap + let value = EVM.Balance(attoflow: 0) + // Call the WFLOW contract which should complete the unwrap + let result = self.coa.call( + to: self.wflowAddress, + data: calldata, + gasLimit: 15_000_000, + value: value + ) + assert(result.status == EVM.Status.successful, message: "Failed to wrap FLOW as WFLOW") + self.postBalance = UInt(FlowEVMBridgeUtils.balanceOf(owner: self.coa.address(), evmContractAddress: self.wflowAddress)) + } + + post { + self.postBalance == self.preBalance - UInt(amount): + "Incorrect post balance - expected=".concat((self.preBalance - UInt(amount)).toString()) + .concat(" | actual=").concat(self.postBalance.toString()) + } +} diff --git a/cadence/transactions/example-assets/evm-assets/wrap_flow.cdc b/cadence/transactions/example-assets/evm-assets/wrap_flow.cdc new file mode 100644 index 00000000..d29974b1 --- /dev/null +++ b/cadence/transactions/example-assets/evm-assets/wrap_flow.cdc @@ -0,0 +1,42 @@ +import "FungibleToken" +import "FlowToken" + +import "EVM" + +/// This transactions wraps FLOW tokens as WFLOW tokens, using the signing COA's EVM FLOW balance primarily. If the +/// EVM balance is insufficient, the transaction will transfer FLOW from the Cadence balance to the EVM balance. +/// +/// @param wflowContractHex: The EVM address of the WFLOW contract as a hex string +/// @param amount: The amount of FLOW to wrap as WFLOW +/// +transaction(wflowContractHex: String, amount: UFix64) { + let coa: auth(EVM.Call) &EVM.CadenceOwnedAccount + let vault: auth(FungibleToken.Withdraw) &FlowToken.Vault + + prepare(signer: auth(BorrowValue) &Account) { + self.coa = signer.storage.borrow(from: /storage/evm) + ?? panic("Could not borrow COA from provided gateway address") + self.vault = signer.storage.borrow(from: /storage/flowTokenVault) + ?? panic("Missing FLOW vault") + } + + execute { + // Transfer from Cadence balance to EVM balance if EVM balance is insufficient + let evmBalance = self.coa.balance().inFLOW() + if evmBalance < amount { + let fundVault <- self.vault.withdraw(amount: amount - evmBalance) as! @FlowToken.Vault + self.coa.deposit(from: <-fundVault) + } + // Define the value to send to the WFLOW contract + let balance = EVM.Balance(attoflow: 0) + balance.setFLOW(flow: amount) + let calldata = EVM.encodeABIWithSignature("deposit()", []) + let result = self.coa.call( + to: EVM.addressFromString(wflowContractHex), + data: calldata, + gasLimit: 15_000_000, + value: balance + ) + assert(result.status == EVM.Status.successful, message: "Failed to wrap FLOW as WFLOW") + } +} diff --git a/solidity/src/handled-assets/WETH9.sol b/solidity/src/handled-assets/WETH9.sol new file mode 100644 index 00000000..a592dc02 --- /dev/null +++ b/solidity/src/handled-assets/WETH9.sol @@ -0,0 +1,756 @@ +// Copyright (C) 2015, 2016, 2017 Dapphub + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +pragma solidity >=0.4.22 <0.6; + +contract WETH9 { + string public name = "Wrapped Flow"; + string public symbol = "WFLOW"; + uint8 public decimals = 18; + + event Approval(address indexed src, address indexed guy, uint wad); + event Transfer(address indexed src, address indexed dst, uint wad); + event Deposit(address indexed dst, uint wad); + event Withdrawal(address indexed src, uint wad); + + mapping (address => uint) public balanceOf; + mapping (address => mapping (address => uint)) public allowance; + + function() external payable { + deposit(); + } + function deposit() public payable { + balanceOf[msg.sender] += msg.value; + emit Deposit(msg.sender, msg.value); + } + function withdraw(uint wad) public { + require(balanceOf[msg.sender] >= wad); + balanceOf[msg.sender] -= wad; + msg.sender.transfer(wad); + emit Withdrawal(msg.sender, wad); + } + + function totalSupply() public view returns (uint) { + return address(this).balance; + } + + function approve(address guy, uint wad) public returns (bool) { + allowance[msg.sender][guy] = wad; + emit Approval(msg.sender, guy, wad); + return true; + } + + function transfer(address dst, uint wad) public returns (bool) { + return transferFrom(msg.sender, dst, wad); + } + + function transferFrom(address src, address dst, uint wad) + public + returns (bool) + { + require(balanceOf[src] >= wad); + + if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { + require(allowance[src][msg.sender] >= wad); + allowance[src][msg.sender] -= wad; + } + + balanceOf[src] -= wad; + balanceOf[dst] += wad; + + emit Transfer(src, dst, wad); + + return true; + } +} + + +/* + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +*/ \ No newline at end of file From 940d1741aa1e206fa38ae2ee2ca4669150c2e10b Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Tue, 22 Oct 2024 16:36:37 -0600 Subject: [PATCH 06/13] remove previewnet from flow.json --- flow.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/flow.json b/flow.json index d345b271..a0f1f3f9 100644 --- a/flow.json +++ b/flow.json @@ -264,7 +264,6 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "e467b9dd11fa00df", - "previewnet": "b6763b4399a888c8", "testnet": "8c5303eaa26202d6" } }, @@ -274,7 +273,6 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "e467b9dd11fa00df", - "previewnet": "b6763b4399a888c8", "testnet": "8c5303eaa26202d6" } }, @@ -284,7 +282,6 @@ "aliases": { "emulator": "0ae53cb6e3f42a79", "mainnet": "1654653399040a61", - "previewnet": "4445e7ad11568276", "testnet": "7e60df042a9c0868" } }, @@ -294,7 +291,6 @@ "aliases": { "emulator": "ee82856bf20e2aa6", "mainnet": "f233dcee88fe0abe", - "previewnet": "a0225e7000ac82a9", "testnet": "9a0766d93b6608b7" } }, @@ -304,7 +300,6 @@ "aliases": { "emulator": "ee82856bf20e2aa6", "mainnet": "f233dcee88fe0abe", - "previewnet": "a0225e7000ac82a9", "testnet": "9a0766d93b6608b7" } }, @@ -314,7 +309,6 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", - "previewnet": "b6763b4399a888c8", "testnet": "631e88ae7f1d7c20" } }, @@ -324,7 +318,6 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", - "previewnet": "b6763b4399a888c8", "testnet": "631e88ae7f1d7c20" } }, @@ -334,7 +327,6 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", - "previewnet": "b6763b4399a888c8", "testnet": "631e88ae7f1d7c20" } } From 6ddfaaf3bb1fc480beb5922b5fd3cd3091474a28 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Mon, 2 Dec 2024 17:44:15 -0700 Subject: [PATCH 07/13] update Handler interfaces and WFLOWTokenHandler impl --- .../bridge/FlowEVMBridgeHandlers.cdc | 49 ++++++++++--------- .../FlowEVMBridgeHandlerInterfaces.cdc | 36 ++++++++++---- 2 files changed, 52 insertions(+), 33 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index 635d706f..dea4350b 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -192,6 +192,14 @@ access(all) contract FlowEVMBridgeHandlers { } } + /** + TODO: + - Configure handler + - + - Update association between FLOW & WFLOW + - Remove any pre-conditions on FLOW in bridging functionality + */ + /// Facilitates moving Flow between Cadence and EVM as WFLOW. Since WFLOW is an artifact of the EVM ecosystem, /// wrapping the native token as an ERC20, it does not have a place in Cadence's fungible token ecosystem. /// Given the native interface on EVM.CadenceOwnedAccount and EVM.EVMAddress to move FLOW between Cadence and EVM, @@ -243,11 +251,6 @@ access(all) contract FlowEVMBridgeHandlers { tokens: @{FungibleToken.Vault}, to: EVM.EVMAddress ) { - pre { - tokens.getType() == Type<@FlowToken.Vault>(): - "Invalid token type=".concat(tokens.getType().identifier) - .concat(" - WFLOWTokenHandler only handles FlowToken Vault") - } let flowVault <- tokens as! @FlowToken.Vault let wflowAddress = self.getTargetEVMAddress()! @@ -276,14 +279,14 @@ access(all) contract FlowEVMBridgeHandlers { // Cover underflow assert( postBalance > preBalance, - message: "Balance decremented after wrapping FLOW" + message: "Escrowed WFLOW balance did not increment after wrapping FLOW" ) // Confirm bridge COA's WFLOW balance has incremented by the expected amount assert( postBalance - preBalance == uintAmount, - message: "Balance after wrapping FLOW does not match requested amount - expected=" + message: "Balance after wrapping FLOW does not match requested amount - expected " .concat((preBalance + uintAmount).toString()) - .concat(" actual=") + .concat(" but got ") .concat((postBalance - preBalance).toString()) ) @@ -315,7 +318,11 @@ access(all) contract FlowEVMBridgeHandlers { amount, erc20Address: wflowAddress ) - assert(ufixAmount > 0.0, message: "Amount to bridge must be greater than 0") + assert( + ufixAmount > 0.0, + message: "Requested UInt256 amount ".concat(amount.toString()).concat(" converted to 0.0 ") + .concat(" - try bridging a larger amount to avoid UFix64 precision loss during conversion") + ) // Transfers WFLOW to bridge COA as escrow FlowEVMBridgeUtils.mustEscrowERC20( @@ -344,7 +351,7 @@ access(all) contract FlowEVMBridgeHandlers { // Cover underflow assert( postBalance > preBalance, - message: "Balance did not increment after unwrapping WFLOW amount=".concat(amount.toString()) + message: "Escrowed FLOW Balance did not increment after unwrapping WFLOW" ) // Confirm bridge COA's FLOW balance has incremented by the expected amount assert( @@ -355,7 +362,7 @@ access(all) contract FlowEVMBridgeHandlers { .concat((postBalance - preBalance).toString()) ) - // Withdraw FLOW from bridge COA + // Withdraw escrowed FLOW from bridge COA let withdrawBalance = EVM.Balance(attoflow: UInt(amount)) assert( UInt256(withdrawBalance.attoflow) == amount, @@ -367,9 +374,9 @@ access(all) contract FlowEVMBridgeHandlers { let flowVault <- coa.withdraw(balance: withdrawBalance) assert( flowVault.balance == ufixAmount, - message: "Vault balance does not match requested amount - expected=" + message: "Resulting Vault balance does not match requested amount - expected " .concat(ufixAmount.toString()) - .concat(" actual=") + .concat(" but returned ") .concat(flowVault.balance.toString()) ) return <-flowVault @@ -380,13 +387,15 @@ access(all) contract FlowEVMBridgeHandlers { /// Sets the target type for the handler access(FlowEVMBridgeHandlerInterfaces.Admin) fun setTargetType(_ type: Type) { - panic("WFLOWTokenHandler has targetType set at initialization") + panic("WFLOWTokenHandler has targetType set to " + .concat(self.targetType.identifier).concat(" at initialization")) } /// Sets the target EVM address for the handler access(FlowEVMBridgeHandlerInterfaces.Admin) fun setTargetEVMAddress(_ address: EVM.EVMAddress) { - panic("WFLOWTokenHandler has EVMAddress set at initialization") + panic("WFLOWTokenHandler has EVMAddress set to " + .concat(self.targetEVMAddress.toString()).concat(" at initialization")) } /// Sets the target type for the handler @@ -400,14 +409,6 @@ access(all) contract FlowEVMBridgeHandlers { fun enableBridging() { self.enabled = true } - - /* --- Internal --- */ - - /// Returns an entitled reference to the encapsulated minter resource - access(self) - view fun borrowMinter(): auth(FlowEVMBridgeHandlerInterfaces.Mint) &{FlowEVMBridgeHandlerInterfaces.TokenMinter}? { - return nil - } } /// This resource enables the configuration of Handlers. These Handlers are stored in FlowEVMBridgeConfig from which @@ -417,7 +418,7 @@ access(all) contract FlowEVMBridgeHandlers { /// Creates a new Handler and adds it to the bridge configuration /// /// @param handlerType: The type of handler to create as defined in this contract - /// @param targetType: The type of the asset the handler will handle. + /// @param targetType: The type of the asset the handler will handle /// @param targetEVMAddress: The EVM contract address the handler will handle, can be nil if still unknown /// @param expectedMinterType: The Type of the expected minter to be set for the created TokenHandler /// diff --git a/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc b/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc index 5ef15275..3ec0dbdd 100644 --- a/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc +++ b/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc @@ -99,8 +99,8 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { access(Admin) fun enableBridging() { pre { self.getTargetType() != nil && self.getTargetEVMAddress() != nil: - "Cannot enable before setting bridge targets" - !self.isEnabled(): "Handler already enabled" + "Cannot enable before setting bridge target Type and EVM Address" + !self.isEnabled(): "Handler has already been enabled" } post { self.isEnabled(): "Problem enabling Handler" @@ -122,11 +122,16 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { /// Mints the specified amount of tokens access(Mint) fun mint(amount: UFix64): @{FungibleToken.Vault} { pre { - amount > 0.0: "Amount must be greater than 0" + amount > 0.0: "Attempting to mint 0.0 - Amount minted must be greater than 0" } post { - result.getType() == self.getMintedType(): "Invalid Vault type returned" - result.balance == amount: "Minted amount does not match requested amount" + result.getType() == self.getMintedType(): + "TokenMinter ".concat(self.getType().identifier).concat(" with uuid ").concat(self.uuid.toString()) + .concat(" expected to mint ").concat(self.getMintedType().identifier) + .concat(" but returned ").concat(result.getType().identifier) + result.balance == amount: + "Minted amount ".concat(result.balance.toString()) + .concat(" does not match requested amount ").concat(amount.toString()) } } } @@ -141,8 +146,15 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { to: EVM.EVMAddress ) { pre { - self.isEnabled(): "Handler is not yet enabled" - tokens.getType() == self.getTargetType(): "Invalid Vault type" + self.isEnabled(): + "TokenHandler ".concat(self.getType().identifier).concat(" with uuid ") + .concat(self.uuid.toString()).concat(" is not yet enabled") + tokens.getType() == self.getTargetType(): + "TokenHandler ".concat(self.getType().identifier).concat(" with uuid ").concat(self.uuid.toString()) + .concat(" expects ").concat(self.getTargetType()?.identifier ?? "nil") + .concat(" but received ").concat(tokens.getType().identifier) + tokens.balance > 0.0: + "Attempting to bridge 0.0 tokens - zero amounts are unsupported" } } /// Fulfills a request to bridge tokens from the EVM side to the Cadence side @@ -153,10 +165,16 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { protectedTransferCall: fun (): EVM.Result ): @{FungibleToken.Vault} { pre { - self.isEnabled(): "Handler is not yet enabled" + self.isEnabled(): + "TokenHandler ".concat(self.getType().identifier).concat(" with uuid ") + .concat(self.uuid.toString()).concat(" is not yet enabled") + amount > UInt256(0): "Attempting to bridge 0 tokens from EVM - zero amounts are unsupported" } post { - result.getType() == self.getTargetType(): "Invalid Vault type returned" + result.getType() == self.getTargetType(): + "TokenHandler ".concat(self.getType().identifier).concat(" with uuid ").concat(self.uuid.toString()) + .concat(" expected to return ").concat(self.getTargetType()?.identifier ?? "nil") + .concat(" but returned ").concat(result.getType().identifier) } } } From 8c3241c8254b156fc8a8af5b6b52dd75432f1f5d Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Tue, 3 Dec 2024 16:35:44 -0700 Subject: [PATCH 08/13] fix WFLOWHandler WFLOW withdrawal call --- .../bridge/FlowEVMBridgeHandlers.cdc | 17 ++---- .../tests/flow_evm_wflow_handler_tests.cdc | 55 +++++++++++++++---- .../example-assets/evm-assets/unwrap_flow.cdc | 11 +++- 3 files changed, 58 insertions(+), 25 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index dea4350b..b77d0246 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -192,14 +192,6 @@ access(all) contract FlowEVMBridgeHandlers { } } - /** - TODO: - - Configure handler - - - - Update association between FLOW & WFLOW - - Remove any pre-conditions on FLOW in bridging functionality - */ - /// Facilitates moving Flow between Cadence and EVM as WFLOW. Since WFLOW is an artifact of the EVM ecosystem, /// wrapping the native token as an ERC20, it does not have a place in Cadence's fungible token ecosystem. /// Given the native interface on EVM.CadenceOwnedAccount and EVM.EVMAddress to move FLOW between Cadence and EVM, @@ -338,7 +330,7 @@ access(all) contract FlowEVMBridgeHandlers { // Unwrap the transferred WFLOW to FLOW, giving the bridge COA the necessary FLOW to withdraw from EVM let unwrapResult = FlowEVMBridgeUtils.call( - signature: "withdraw(uint)", + signature: "withdraw(uint256)", targetEVMAddress: wflowAddress, args: [amount], gasLimit: FlowEVMBridgeConfig.gasLimit, @@ -351,7 +343,8 @@ access(all) contract FlowEVMBridgeHandlers { // Cover underflow assert( postBalance > preBalance, - message: "Escrowed FLOW Balance did not increment after unwrapping WFLOW" + message: "Escrowed FLOW Balance did not increment after unwrapping WFLOW - pre: ".concat(preBalance.toString()) + .concat(" post: ").concat(postBalance.toString()) ) // Confirm bridge COA's FLOW balance has incremented by the expected amount assert( @@ -382,7 +375,9 @@ access(all) contract FlowEVMBridgeHandlers { return <-flowVault } - /* --- Admin --- */ + /* --- HandlerAdmin --- */ + // Conforms to HandlerAdmin for enableBridging, but most of the methods are unnecessary given the strict + // association between FLOW and WFLOW /// Sets the target type for the handler access(FlowEVMBridgeHandlerInterfaces.Admin) diff --git a/cadence/tests/flow_evm_wflow_handler_tests.cdc b/cadence/tests/flow_evm_wflow_handler_tests.cdc index a89013d7..e6f3575a 100644 --- a/cadence/tests/flow_evm_wflow_handler_tests.cdc +++ b/cadence/tests/flow_evm_wflow_handler_tests.cdc @@ -5,6 +5,7 @@ import "FungibleToken" import "NonFungibleToken" import "FlowStorageFees" import "EVM" +import "FlowEVMBridgeConfig" import "test_helpers.cdc" @@ -347,7 +348,7 @@ fun testOnboardWFLOWByEVMAddressFails() { Test.expect(onboardingResult, Test.beFailed()) } -/* --- BRIDGING FUNGIBLE TOKENS - Test bridging both Cadence- & EVM-native fungible tokens --- */ +/* --- BRIDGING FLOW to EVM as WFLOW and WFLOW from EVM as FLOW --- */ // Now enable TokenHandler to bridge in both directions access(all) @@ -361,6 +362,22 @@ fun testEnableWFLOWTokenHandlerSucceeds() { // TODO: Validate event emission and values } +// Validate that funds can be bridged from Cadence to EVM, resulting in balance increase in WFLOW as target +access(all) +fun testBridgeZeroFLOWTokenToEVMFails() { + // Attempt bridge 0 FLOW to EVM - should fail + bridgeTokensToEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: flowTokenAccountAddress, + contractName: "FlowToken", + resourceName: "Vault" + ), + amount: 0.0, + beFailed: true + ) +} + // Validate that funds can be bridged from Cadence to EVM, resulting in balance increase in WFLOW as target access(all) fun testBridgeFLOWTokenToEVMFirstSucceeds() { @@ -372,6 +389,7 @@ fun testBridgeFLOWTokenToEVMFirstSucceeds() { var cadenceBalance = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") ?? panic("Problem getting FlowToken balance") Test.assert(cadenceBalance == flowFundingAmount - coaFundingAmount, message: "Invalid Cadence balance") + // Leave some FLOW as it's needed for storage, transaction, and bridge fees let remainder = 1.0 let bridgeAmount = cadenceBalance - remainder @@ -406,9 +424,23 @@ fun testBridgeFLOWTokenToEVMFirstSucceeds() { // With all funds now in EVM, we can test bridging back to Cadence access(all) -fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { +fun testBridgeZeroWFLOWTokenFromEVMSecondFails() { + bridgeTokensFromEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: flowTokenAccountAddress, + contractName: "FlowToken", + resourceName: "Vault" + ), + amount: UInt256(0), + beFailed: true + ) +} - let wflowTotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) +// With all funds now in EVM, we can test bridging back to Cadence +access(all) +fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { + // let wflowTotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) let cadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") ?? panic("Problem getting FlowToken balance") @@ -430,19 +462,20 @@ fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { // Confirm that Alice's balance has been bridged to Cadence let cadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") ?? panic("Problem getting FlowToken balance") - Test.assertEqual(ufixEVMbalance, cadenceBalanceAfter) + let expectedBalanceAfter = cadenceBalanceBefore + ufixEVMbalance - FlowEVMBridgeConfig.baseFee + Test.assertEqual(expectedBalanceAfter, cadenceBalanceAfter) - // Confirm that the ERC20 balance was burned in the process of bridging + // Confirm that the WFLOW balance was transferred out in the process of bridging let evmBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) Test.assertEqual(UInt256(0), evmBalanceAfter) - // // Validate that the ERC20 balance in circulation remained the same - // let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) - // Test.assertEqual(wflowTotalSupplyBefore, erc20TotalSupplyAfter) + // Validate that the WFLOW supply in circulation reduced to 0 + let wflowTotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) + Test.assertEqual(UInt256(0), wflowTotalSupplyAfter) - // // Validate that all ERC20 funds are now in escrow since all bridged to Cadence - // let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) - // Test.assertEqual(erc20TotalSupplyAfter, escrowBalance) + // Validate that all WFLOW funds are now in escrow since all bridged to Cadence + let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) + Test.assertEqual(wflowTotalSupplyAfter, escrowBalance) } // // Now test bridging with liquidity flow moving entirely from EVM to Cadence and back diff --git a/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc b/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc index a31d85c3..448259ac 100644 --- a/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc +++ b/cadence/transactions/example-assets/evm-assets/unwrap_flow.cdc @@ -5,7 +5,7 @@ import "EVM" import "FlowEVMBridgeUtils" -/// This transactions wraps FLOW tokens as WFLOW tokens, using the signing COA's EVM FLOW balance primarily. If the +/// This transactions wraps FLOW tokens as WFLOW tokens, using the signing COA's EVM FLOW balance primarily. If the /// EVM balance is insufficient, the transaction will transfer FLOW from the Cadence balance to the EVM balance. /// /// @param wflowContractHex: The EVM address of the WFLOW contract as a hex string @@ -22,13 +22,18 @@ transaction(wflowContractHex: String, amount: UInt256) { self.wflowAddress = EVM.addressFromString(wflowContractHex) self.coa = signer.storage.borrow(from: /storage/evm) ?? panic("Could not borrow COA from provided gateway address") + self.preBalance = UInt(FlowEVMBridgeUtils.balanceOf(owner: self.coa.address(), evmContractAddress: self.wflowAddress)) + assert( + self.preBalance >= UInt(amount), + message: "Amount exceeds current WFLOW balance of ".concat(self.preBalance.toString()) + ) self.postBalance = 0 } execute { // Encode the withdraw function call - let calldata = EVM.encodeABIWithSignature("withdraw(uint)", [UInt(amount)]) + let calldata = EVM.encodeABIWithSignature("withdraw(uint256)", [UInt(amount)]) // Define the value to send to the WFLOW contract - 0 to unwrap let value = EVM.Balance(attoflow: 0) // Call the WFLOW contract which should complete the unwrap @@ -38,7 +43,7 @@ transaction(wflowContractHex: String, amount: UInt256) { gasLimit: 15_000_000, value: value ) - assert(result.status == EVM.Status.successful, message: "Failed to wrap FLOW as WFLOW") + assert(result.status == EVM.Status.successful, message: "Failed to unwrap FLOW as WFLOW") self.postBalance = UInt(FlowEVMBridgeUtils.balanceOf(owner: self.coa.address(), evmContractAddress: self.wflowAddress)) } From 7fb155c5b810473efd9f966faa2b48fb3d96d35b Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Wed, 4 Dec 2024 12:37:06 -0700 Subject: [PATCH 09/13] update error messages --- .../bridge/FlowEVMBridgeHandlers.cdc | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index b77d0246..946136fe 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -271,14 +271,15 @@ access(all) contract FlowEVMBridgeHandlers { // Cover underflow assert( postBalance > preBalance, - message: "Escrowed WFLOW balance did not increment after wrapping FLOW" + message: "Escrowed WFLOW balance did not increment after wrapping FLOW - pre: " + .concat(preBalance.toString()).concat(" | post: ").concat(postBalance.toString()) ) // Confirm bridge COA's WFLOW balance has incremented by the expected amount assert( postBalance - preBalance == uintAmount, - message: "Balance after wrapping FLOW does not match requested amount - expected " + message: "Escrowed WFLOW balance after wrapping does not match requested amount - expected: " .concat((preBalance + uintAmount).toString()) - .concat(" but got ") + .concat(" | actual: ") .concat((postBalance - preBalance).toString()) ) @@ -344,14 +345,14 @@ access(all) contract FlowEVMBridgeHandlers { assert( postBalance > preBalance, message: "Escrowed FLOW Balance did not increment after unwrapping WFLOW - pre: ".concat(preBalance.toString()) - .concat(" post: ").concat(postBalance.toString()) + .concat(" | post: ").concat(postBalance.toString()) ) // Confirm bridge COA's FLOW balance has incremented by the expected amount assert( UInt256(postBalance - preBalance) == amount, - message: "Balance after unwrapping WFLOW does not match requested amount - expected=" + message: "Escrowed WFLOW balance after unwrapping does not match requested amount - expected: " .concat((UInt256(preBalance) + amount).toString()) - .concat(" actual=") + .concat(" | actual: ") .concat((postBalance - preBalance).toString()) ) @@ -359,17 +360,17 @@ access(all) contract FlowEVMBridgeHandlers { let withdrawBalance = EVM.Balance(attoflow: UInt(amount)) assert( UInt256(withdrawBalance.attoflow) == amount, - message: "Balance failed to convert to attoflow - expected=" + message: "Requested balance failed to convert to attoflow - expected: " .concat(amount.toString()) - .concat(" actual=") + .concat(" | actual: ") .concat(withdrawBalance.attoflow.toString()) ) let flowVault <- coa.withdraw(balance: withdrawBalance) assert( flowVault.balance == ufixAmount, - message: "Resulting Vault balance does not match requested amount - expected " + message: "Resulting FLOW Vault balance does not match requested amount - expected: " .concat(ufixAmount.toString()) - .concat(" but returned ") + .concat(" | actual: ") .concat(flowVault.balance.toString()) ) return <-flowVault From 9708f102cea0601c2efe8ded2e3fb857c96b6dac Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Fri, 6 Dec 2024 15:50:59 -0700 Subject: [PATCH 10/13] remove redundant test case --- cadence/tests/flow_evm_bridge_tests.cdc | 35 ------ .../tests/flow_evm_wflow_handler_tests.cdc | 111 ------------------ 2 files changed, 146 deletions(-) diff --git a/cadence/tests/flow_evm_bridge_tests.cdc b/cadence/tests/flow_evm_bridge_tests.cdc index 3a95166e..2a4649d9 100644 --- a/cadence/tests/flow_evm_bridge_tests.cdc +++ b/cadence/tests/flow_evm_bridge_tests.cdc @@ -467,41 +467,6 @@ fun testCreateCOASucceeds() { let bobCOAAddress = getCOAAddressHex(atFlowAddress: bob.address) } -access(all) -fun testBridgeFlowToEVMSucceeds() { - // Get $FLOW balances before, making assertions based on values from previous case - let cadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") - ?? panic("Problem getting $FLOW balance") - Test.assertEqual(900.0, cadenceBalanceBefore) - - // Get EVM $FLOW balance before - var aliceCOAAddressHex = getCOAAddressHex(atFlowAddress: alice.address) - - let evmBalanceBefore = getEVMFlowBalance(of: aliceCOAAddressHex) - Test.assertEqual(100.0, evmBalanceBefore) - - // Execute bridge to EVM - let bridgeAmount = 100.0 - bridgeTokensToEVM( - signer: alice, - vaultIdentifier: buildTypeIdentifier( - address: Address(0x03), - contractName: "FlowToken", - resourceName: "Vault" - ), amount: bridgeAmount, - beFailed: false - ) - - // Confirm Alice's token balance is now 0.0 - let cadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") - ?? panic("Problem getting $FLOW balance") - Test.assertEqual(cadenceBalanceBefore - bridgeAmount, cadenceBalanceAfter) - - // Confirm balance on EVM side has been updated - let evmBalanceAfter = getEVMFlowBalance(of: aliceCOAAddressHex) - Test.assertEqual(evmBalanceBefore + bridgeAmount, evmBalanceAfter) -} - access(all) fun testMintExampleNFTSucceeds() { let setupCollectionResult = executeTransaction( diff --git a/cadence/tests/flow_evm_wflow_handler_tests.cdc b/cadence/tests/flow_evm_wflow_handler_tests.cdc index e6f3575a..3135b8f3 100644 --- a/cadence/tests/flow_evm_wflow_handler_tests.cdc +++ b/cadence/tests/flow_evm_wflow_handler_tests.cdc @@ -477,114 +477,3 @@ fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) Test.assertEqual(wflowTotalSupplyAfter, escrowBalance) } - -// // Now test bridging with liquidity flow moving entirely from EVM to Cadence and back -// access(all) -// fun testBridgeWFLOWTokenFromEVMFirstSucceeds() { -// // Reset to snapshot before bridging between VMs -// Test.reset(to: snapshot) - - -// var erc20TotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) -// let cadenceTotalSupplyBefore = getCadenceTotalSupply( -// contractAddress: flowTokenAccountAddress, -// contractName: "FlowToken", -// vaultIdentifier: flowTokenIdentifier -// ) ?? panic("Problem getting total supply of Cadence tokens") -// let uintCadenceTotalSupplyBefore = ufix64ToUInt256(cadenceTotalSupplyBefore, decimals: defaultDecimals) -// Test.assertEqual(uintCadenceTotalSupplyBefore + erc20MintAmount, erc20TotalSupplyBefore) - -// // Alice should start with amount previously minted -// let aliceEVMBalanceBefore = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) -// Test.assertEqual(erc20MintAmount, aliceEVMBalanceBefore) -// // Cadence total supply should match the amount in escrow -// let escrowBalanceBefore = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) -// Test.assertEqual(uintCadenceTotalSupplyBefore, escrowBalanceBefore) - -// // Alice was the only one minted Cadence tokens, so should have the total supply in Cadence -// let aliceCadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") -// ?? panic("Problem getting FlowToken balance") -// Test.assertEqual(flowTokenMintAmount, aliceCadenceBalanceBefore) -// Test.assertEqual(cadenceTotalSupplyBefore, aliceCadenceBalanceBefore) - -// // Convert the bridge amount to UFix64 for Cadence balance comparison -// let ufixBridgeAmount = uint256ToUFix64(erc20MintAmount, decimals: defaultDecimals) - -// // Execute bridge from EVM -// bridgeTokensFromEVM( -// signer: alice, -// vaultIdentifier: buildTypeIdentifier( -// address: flowTokenAccountAddress, -// contractName: "FlowToken", -// resourceName: "Vault" -// ), -// amount: aliceEVMBalanceBefore, -// beFailed: false -// ) - -// // Confirm that Alice's balance is now the total supply, having incremented by the amount bridged into Cadence -// let aliceCadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") -// ?? panic("Problem getting FlowToken balance") -// let cadenceTotalSupplyAfter = getCadenceTotalSupply( -// contractAddress: flowTokenAccountAddress, -// contractName: "FlowToken", -// vaultIdentifier: flowTokenIdentifier -// ) ?? panic("Problem getting total supply of Cadence tokens") -// Test.assertEqual(cadenceTotalSupplyAfter, aliceCadenceBalanceAfter) -// Test.assertEqual(cadenceTotalSupplyAfter, cadenceTotalSupplyBefore + ufixBridgeAmount) - -// // Confirm Alice's EVM balance is now 0 -// let aliceEVMBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) -// Test.assertEqual(UInt256(0), aliceEVMBalanceAfter) - -// // Confirm that the amount in escrow incremented -// let escrowBalanceAfter = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) -// Test.assertEqual(escrowBalanceBefore + aliceEVMBalanceBefore, escrowBalanceAfter) - -// // Ensure the ERC20 balance in circulation remained the same -// let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) -// Test.assertEqual(erc20TotalSupplyBefore, erc20TotalSupplyAfter) -// } - -// // Now return all liquidity back to EVM -// access(all) -// fun testBridgeFLOWTokenToEVMSecondSucceeds() { - -// let erc20TotalSupplyBefore = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) - -// // Alice should start with amount previously minted -// let aliceEVMBalanceBefore = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) -// Test.assertEqual(UInt256(0), aliceEVMBalanceBefore) -// let aliceCadenceBalanceBefore = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") -// ?? panic("Problem getting FlowToken balance") - -// // Convert the bridge amount to UInt256 for EVM balance comparison -// let uintBridgeAmount = ufix64ToUInt256(aliceCadenceBalanceBefore, decimals: defaultDecimals) - -// // Execute bridge to EVM -// bridgeTokensToEVM( -// signer: alice, -// vaultIdentifier: buildTypeIdentifier( -// address: flowTokenAccountAddress, -// contractName: "FlowToken", -// resourceName: "Vault" -// ), amount: aliceCadenceBalanceBefore, -// beFailed: false -// ) - -// let aliceCadenceBalanceAfter = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") -// ?? panic("Problem getting FlowToken balance") -// Test.assertEqual(0.0, aliceCadenceBalanceAfter) - -// // Confirm ownership on EVM side with Alice COA as owner of ERC721 representation -// let aliceEVMBalanceAfter = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: wflowAddressHex) -// Test.assertEqual(uintBridgeAmount, aliceEVMBalanceAfter) - -// // Confirm that the ERC20 balance in circulation remained the same -// let erc20TotalSupplyAfter = getEVMTotalSupply(erc20AddressHex: wflowAddressHex) -// Test.assertEqual(erc20TotalSupplyBefore, erc20TotalSupplyAfter) - -// // Confirm escrow balance is now 0 -// let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) -// Test.assertEqual(UInt256(0), escrowBalance) -// } From 80afa22d61b2d89b9aac6ea07639f39a5f6be5e0 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Fri, 6 Dec 2024 16:29:44 -0700 Subject: [PATCH 11/13] update README --- README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7794a239..66c7c60c 100644 --- a/README.md +++ b/README.md @@ -88,9 +88,17 @@ side, it must escrow on the other as the native VM contract is owned by an exter With fungible tokens in particular, there may be some cases where the Cadence contract is not deployed to the bridge account, but the bridge still follows a mint/burn pattern in Cadence. These cases are handled via -[`TokenHandler`](./cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc) implementations. Also know -that moving $FLOW to EVM is built into the `EVMAddress` object so any requests bridging $FLOW to EVM will simply -leverage this interface; however, moving $FLOW from EVM to Cadence must be done through the COA resource. +[`TokenHandler`](./cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc) implementations. + +Also know that moving $FLOW to EVM is built into the `EVMAddress` object via `EVMAddress.deposit(from: @FlowToken.Vault)`. +Conversely, moving $FLOW from EVM is facilitated via the `CadenceOwnedAccount.withdraw(balance: Balance): @FlowToken.Vault` +method. Given these existing interfaces, the bridge instead handles $FLOW as corresponding fungible token +implementations - `FungibleToken.Vault` in Cadence & ERC20 in EVM. Therefore, the bridge wraps $FLOW en route to EVM +(depositing WFLOW to the recipient) and unwraps WFLOW when bridging when moving from EVM. In short, the cross-VM +association for $FLOW as far as the bridge is concerned is `@FlowToken.Vault` <> WFLOW +(`0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e` on +[Testnet](https://evm-testnet.flowscan.io/address/0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e) & +[Mainnet](https://evm.flowscan.io/address/0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e)). Below are transactions relevant to bridging fungible tokens: - [`bridge_tokens_to_evm.cdc`](./cadence/transactions/bridge/tokens/bridge_tokens_to_evm.cdc) From 769a6a111c2787e5940596d4f3b07042d42d4968 Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Tue, 17 Dec 2024 16:00:41 -0800 Subject: [PATCH 12/13] add TokenHandler disabling path & tests --- .../contracts/bridge/FlowEVMBridgeConfig.cdc | 22 ++++++++++++++- .../bridge/FlowEVMBridgeHandlers.cdc | 27 ++++++++++++------ .../FlowEVMBridgeHandlerInterfaces.cdc | 26 +++++++++++++++++ .../tests/flow_evm_bridge_handler_tests.cdc | 28 +++++++++++++++++++ .../tests/flow_evm_wflow_handler_tests.cdc | 25 +++++++++++++++++ .../token-handler/disable_token_handler.cdc | 25 +++++++++++++++++ 6 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 cadence/transactions/bridge/admin/token-handler/disable_token_handler.cdc diff --git a/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc b/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc index d598ef2b..c37307a1 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeConfig.cdc @@ -453,7 +453,7 @@ contract FlowEVMBridgeConfig { access(FlowEVMBridgeHandlerInterfaces.Admin) fun enableHandler(targetType: Type) { let handler = FlowEVMBridgeConfig.borrowTokenHandlerAdmin(targetType) - ?? panic("No handler found for target Type") + ?? panic("No handler found for target Type ".concat(targetType.identifier)) handler.enableBridging() let targetEVMAddressHex = handler.getTargetEVMAddress()?.toString() @@ -465,6 +465,26 @@ contract FlowEVMBridgeConfig { isEnabled: handler.isEnabled() ) } + + /// Disables the TokenHandler for the given Type. If a TokenHandler does not exist for the given Type, the + /// operation reverts. + /// + /// @param targetType: Cadence type indexing the relevant TokenHandler + /// + /// @emits HandlerConfigured with the target Type, target EVM address, and whether the handler is enabled + /// + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun disableHandler(targetType: Type) { + let handler = FlowEVMBridgeConfig.borrowTokenHandlerAdmin(targetType) + ?? panic("No handler found for target Type".concat(targetType.identifier)) + handler.disableBridging() + + emit HandlerConfigured( + targetType: handler.getTargetType()!.identifier, + targetEVMAddress: handler.getTargetEVMAddress()?.toString(), + isEnabled: handler.isEnabled() + ) + } } init() { diff --git a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc index 946136fe..986f8ed7 100644 --- a/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc +++ b/cadence/contracts/bridge/FlowEVMBridgeHandlers.cdc @@ -146,7 +146,8 @@ access(all) contract FlowEVMBridgeHandlers { ) // After state confirmation, mint the tokens and return - let minter = self.borrowMinter() ?? panic("Minter not set") + let minter = self.borrowMinter() + ?? panic("Cannot bridge - Minter not set in ".concat(self.getType().identifier)) let minted <- minter.mint(amount: ufixAmount) return <-minted } @@ -169,20 +170,26 @@ access(all) contract FlowEVMBridgeHandlers { access(FlowEVMBridgeHandlerInterfaces.Admin) fun setMinter(_ minter: @{FlowEVMBridgeHandlerInterfaces.TokenMinter}) { pre { - self.minter == nil: "Minter has already been set" + self.minter == nil: "Minter has already been set in ".concat(self.getType().identifier) } self.minter <-! minter } - /// Enables the handler for request handling. The + /// Enables the handler for request handling. access(FlowEVMBridgeHandlerInterfaces.Admin) fun enableBridging() { pre { - self.minter != nil: "Cannot enable handler without a minter" + self.minter != nil: "Cannot enable ".concat(self.getType().identifier).concat(" without a minter") } self.enabled = true } + /// Disables the handler for request handling. + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun disableBridging() { + self.enabled = false + } + /* --- Internal --- */ /// Returns an entitled reference to the encapsulated minter resource @@ -200,11 +207,9 @@ access(all) contract FlowEVMBridgeHandlers { access(all) resource WFLOWTokenHandler : FlowEVMBridgeHandlerInterfaces.TokenHandler { /// Flag determining if request handling is enabled access(self) var enabled: Bool - /// The Cadence Type this handler fulfills requests for. This field is optional in the event the Cadence token - /// contract address is not yet known but the EVM Address must still be filtered via Handler to prevent the - /// contract from being onboarded otherwise. + /// The Cadence Type this handler fulfills requests for access(self) var targetType: Type - /// The EVM contract address this handler fulfills requests for. + /// The EVM contract address this handler fulfills requests for access(self) var targetEVMAddress: EVM.EVMAddress init(wflowEVMAddress: EVM.EVMAddress) { @@ -405,6 +410,12 @@ access(all) contract FlowEVMBridgeHandlers { fun enableBridging() { self.enabled = true } + + /// Disables the handler for request handling. + access(FlowEVMBridgeHandlerInterfaces.Admin) + fun disableBridging() { + self.enabled = false + } } /// This resource enables the configuration of Handlers. These Handlers are stored in FlowEVMBridgeConfig from which diff --git a/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc b/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc index 3ec0dbdd..e22869d4 100644 --- a/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc +++ b/cadence/contracts/bridge/interfaces/FlowEVMBridgeHandlerInterfaces.cdc @@ -33,6 +33,14 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { targetType: String, targetEVMAddress: String ) + /// Event emitted when a handler is disabled, pausing bridging between VMs + access(all) event HandlerDisabled( + handlerType: String, + handlerUUID: UInt64, + targetType: String?, + targetEVMAddress: String? + ) + /// Emitted when a minter resource is set in a handler access(all) event MinterSet(handlerType: String, handlerUUID: UInt64, targetType: String?, @@ -112,6 +120,24 @@ access(all) contract FlowEVMBridgeHandlerInterfaces { ) } } + + /// Disables the Handler from fulfilling bridge requests. + access(Admin) fun disableBridging() { + pre { + self.isEnabled(): + "Cannot disable: ".concat(self.getType().identifier).concat(" is already disabled") + } + post { + !self.isEnabled(): + "Problem disabling ".concat(self.getType().identifier) + emit HandlerDisabled( + handlerType: self.getType().identifier, + handlerUUID: self.uuid, + targetType: self.getTargetType()?.identifier, + targetEVMAddress: self.getTargetEVMAddress()?.toString() + ) + } + } } /// Minter interface for configurations requiring the minting of Cadence fungible tokens diff --git a/cadence/tests/flow_evm_bridge_handler_tests.cdc b/cadence/tests/flow_evm_bridge_handler_tests.cdc index a067d01f..bd176464 100644 --- a/cadence/tests/flow_evm_bridge_handler_tests.cdc +++ b/cadence/tests/flow_evm_bridge_handler_tests.cdc @@ -720,3 +720,31 @@ fun testBridgeHandledCadenceNativeTokenToEVMSecondSucceeds() { let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: erc20AddressHex) Test.assertEqual(UInt256(0), escrowBalance) } + +// After disabling the handler, funds should not move between VMs +access(all) +fun testBridgeHandledCadenceNativeTokenAfterDisablingFails() { + let disabledResult = executeTransaction( + "../transactions/bridge/admin/token-handler/disable_token_handler.cdc", + [exampleTokenIdentifier], + bridgeAccount + ) + Test.expect(disabledResult, Test.beSucceeded()) + + let aliceCOAAddressHex = getCOAAddressHex(atFlowAddress: alice.address) + + // Execute bridge from EVM, bridging Alice's full balance to Cadence + let evmBalance = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: erc20AddressHex) + let ufixEVMbalance = uint256ToUFix64(evmBalance, decimals: defaultDecimals) + log("ufixEVMbalance: ".concat(ufixEVMbalance.toString())) + bridgeTokensFromEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: exampleHandledTokenAccount.address, + contractName: "ExampleHandledToken", + resourceName: "Vault" + ), + amount: evmBalance, + beFailed: true + ) +} \ No newline at end of file diff --git a/cadence/tests/flow_evm_wflow_handler_tests.cdc b/cadence/tests/flow_evm_wflow_handler_tests.cdc index 3135b8f3..0308913b 100644 --- a/cadence/tests/flow_evm_wflow_handler_tests.cdc +++ b/cadence/tests/flow_evm_wflow_handler_tests.cdc @@ -477,3 +477,28 @@ fun testBridgeWFLOWTokenFromEVMSecondSucceeds() { let escrowBalance = balanceOf(evmAddressHex: getBridgeCOAAddressHex(), erc20AddressHex: wflowAddressHex) Test.assertEqual(wflowTotalSupplyAfter, escrowBalance) } + +access(all) +fun testBridgeWFLOWToCadenceAfterDisablingFails() { + let disabledResult = executeTransaction( + "../transactions/bridge/admin/token-handler/disable_token_handler.cdc", + [flowTokenIdentifier], + bridgeAccount + ) + Test.expect(disabledResult, Test.beSucceeded()) + + let cadenceBalance = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") + ?? panic("Problem getting FlowToken balance") + log("cadenceBalance:" .concat(cadenceBalance.toString())) + + bridgeTokensToEVM( + signer: alice, + vaultIdentifier: buildTypeIdentifier( + address: flowTokenAccountAddress, + contractName: "FlowToken", + resourceName: "Vault" + ), + amount: cadenceBalance, + beFailed: true + ) +} \ No newline at end of file diff --git a/cadence/transactions/bridge/admin/token-handler/disable_token_handler.cdc b/cadence/transactions/bridge/admin/token-handler/disable_token_handler.cdc new file mode 100644 index 00000000..1a10adbc --- /dev/null +++ b/cadence/transactions/bridge/admin/token-handler/disable_token_handler.cdc @@ -0,0 +1,25 @@ +import "EVM" + +import "FlowEVMBridgeHandlerInterfaces" +import "FlowEVMBridgeConfig" + +/// Disables the TokenHandler from fulfilling bridge requests. +/// +/// @param targetTypeIdentifier: The identifier of the handler's target type. +/// +transaction(targetTypeIdentifier: String) { + + let admin: auth(FlowEVMBridgeHandlerInterfaces.Admin) &FlowEVMBridgeConfig.Admin + + prepare(signer: auth(BorrowValue) &Account) { + self.admin = signer.storage.borrow( + from: FlowEVMBridgeConfig.adminStoragePath + ) ?? panic("Could not borrow FlowEVMBridgeConfig Admin reference") + } + + execute { + let targetType = CompositeType(targetTypeIdentifier) + ?? panic("Invalid Type identifier provided") + self.admin.disableHandler(targetType: targetType) + } +} From 215b6e1809b396209db87a73f28c6a9784f8ae6c Mon Sep 17 00:00:00 2001 From: Giovanni Sanchez <108043524+sisyphusSmiling@users.noreply.github.com> Date: Tue, 17 Dec 2024 16:05:30 -0800 Subject: [PATCH 13/13] remove unused test lines --- cadence/tests/flow_evm_bridge_handler_tests.cdc | 4 ---- cadence/tests/flow_evm_wflow_handler_tests.cdc | 1 - 2 files changed, 5 deletions(-) diff --git a/cadence/tests/flow_evm_bridge_handler_tests.cdc b/cadence/tests/flow_evm_bridge_handler_tests.cdc index bd176464..cae23e84 100644 --- a/cadence/tests/flow_evm_bridge_handler_tests.cdc +++ b/cadence/tests/flow_evm_bridge_handler_tests.cdc @@ -732,11 +732,7 @@ fun testBridgeHandledCadenceNativeTokenAfterDisablingFails() { Test.expect(disabledResult, Test.beSucceeded()) let aliceCOAAddressHex = getCOAAddressHex(atFlowAddress: alice.address) - - // Execute bridge from EVM, bridging Alice's full balance to Cadence let evmBalance = balanceOf(evmAddressHex: aliceCOAAddressHex, erc20AddressHex: erc20AddressHex) - let ufixEVMbalance = uint256ToUFix64(evmBalance, decimals: defaultDecimals) - log("ufixEVMbalance: ".concat(ufixEVMbalance.toString())) bridgeTokensFromEVM( signer: alice, vaultIdentifier: buildTypeIdentifier( diff --git a/cadence/tests/flow_evm_wflow_handler_tests.cdc b/cadence/tests/flow_evm_wflow_handler_tests.cdc index 0308913b..ad2e5fb5 100644 --- a/cadence/tests/flow_evm_wflow_handler_tests.cdc +++ b/cadence/tests/flow_evm_wflow_handler_tests.cdc @@ -489,7 +489,6 @@ fun testBridgeWFLOWToCadenceAfterDisablingFails() { let cadenceBalance = getBalance(ownerAddr: alice.address, storagePathIdentifier: "flowTokenVault") ?? panic("Problem getting FlowToken balance") - log("cadenceBalance:" .concat(cadenceBalance.toString())) bridgeTokensToEVM( signer: alice,