Smart contracts for Ref Finance

Overview

Ref Finance Contracts

This mono repo contains the source code for the smart contracts of Ref Finance on NEAR.

Contracts

Contract Reference Description
test-token - Test token contract
ref-exchange docs Main exchange contract, that allows to deposit and withdraw tokens, exchange them via various pools

Development

  1. Install rustup via https://rustup.rs/
  2. Run the following:
rustup default stable
rustup target add wasm32-unknown-unknown

Testing

Contracts have unit tests and also integration tests using NEAR Simulation framework. All together can be run:

cd ref-exchange
cargo test --all

Compiling

You can build release version by running next scripts inside each contract folder:

cd ref-exchange
./build.sh

Deploying to TestNet

To deploy to TestNet, you can use next command:

near dev-deploy

This will output on the contract ID it deployed.

Comments
  • makefile for build/test/release + simple ci for pr/pushes to master

    makefile for build/test/release + simple ci for pr/pushes to master

    • spread build_docker.sh logic into makefile targets
    • basic ci testing for ref-farming and ref-exchange (equivalent of running cargo test in each)

    successful ci tests evidence: https://github.com/fuzzylemma/ref-contracts/actions

    opened by fuzzylemma 2
  • Improve upgrading capability by removing parsing/loading

    Improve upgrading capability by removing parsing/loading

    This reduces amount of gas used and makes it compatible with Sputnik DAO UpdateRemote.

    Usage from CLI:

    > near repl
    const fs = require('fs');
    const account = await near.account("<account>");
    const newContract = fs.readFileSync("<path>");
    const result = account.signAndSendTransaction(
        <contract>,
        [
            nearAPI.transactions.functionCall("upgrade", newContract, 20000000000000, "0"),
        ]);
    

    Example: https://explorer.testnet.near.org/transactions/GLwdTBVTrguY7mERg997MK5mxnfbAkVgW78sKPprhMge

    opened by referencedev 2
  • Direct swap approach

    Direct swap approach

    The idea is to add "direct swap" approach that doesn't require deposit/withdraw in most cases. The way it will work:

    • User calls ft_transfer_call on the token that wants to swap. Passing "<pool_id>:<token_out>:<min_amount>:" as msg
    • Ref Exchange when receiving tokens tries to swap.
    • If successfully swaps (pool is good, token out is there, min amount is met), sends token_out directly to the user
    • Now if that fails (the user is not registered), on callback it records that user has them in portfolio in Ref Exhcange

    Note that user still MUST be register for outgoing token ahead of time to prevent loss of funds in case they are not registered on the receiving end.

    This requirement can be lifted by the caller by passing force=1, if they guarantee that user's account is registered. In case the user is not registered at the end - the funds will be returned to the exchange owner.

    opened by referencedev 2
  • Proposal: require subsequent amount_in in swap actions to be nil.

    Proposal: require subsequent amount_in in swap actions to be nil.

    Proposal

    Currently we only require that the first swap action amount_in is set. In the subsequent actions, however, it's more intuitive to always use the output of the previous action.

    opened by robert-zaremba 2
  • Storage deposit always enforces minimum deposit (even after registration)

    Storage deposit always enforces minimum deposit (even after registration)

    After a user is registered they should be able to deposit amounts smaller than the Account::min_storage_usage.

    Right now it costs 800000000000000000000 to hold a token, but the minimum allowed to deposit is 840000000000000000000. Meaning that you have to over deposit to hold an additional token.

    https://explorer.near.org/transactions/2Qcph7Kc1kC4ifshN1q6cTdhto9XRjj8G8d93CJyA2ZK

    opened by mehtaphysical 2
  • Feature instant swap

    Feature instant swap

    • Instant swap
      • users can swap directly using ft_transfer_call without deposit and withdraw;
      • old users's inner ref assets won't be touched in successful situation;
      • Any failure before swap completion would cause a refund of token_in token back to user's wallet;
      • Any failure after swap completion would cause token_out token into inner account or lost-found account;
    opened by marco-sundsk 1
  • Direct swap

    Direct swap

    This implements #24: allows to swap with a single transaction without needing to deposit / withdraw. Not even storage deposits are required for the pool, if force=1 is passed (but FE must make sure that receiver is registered in the outgoing token)

    Example usage:

            contract.ft_transfer_call(
                to_va(swap()),
                to_yocto("1").into(),
                None,
                format!("{{\"force\": {}, \"actions\": [{{\"pool_id\": 0, \"token_in\": \"dai\", \"token_out\": \"eth\", \"min_amount_out\": \"1\"}}]}}", force)
            ),
    

    Specifically for TokenReceiverMessage message parameters are:

    enum TokenReceiverMessage {
        /// Alternative to deposit + execute actions call.
        Execute {
            referral_id: Option<ValidAccountId>,
            /// If force != 0, doesn't require user to even have account. In case of failure to deposit to the user's outgoing balance, tokens will be returned to the exchange and can be "saved" via governance.
            /// If force == 0, the account for this user still have been registered. If deposit of outgoing tokens will fail, it will deposit it back into the account.
            force: u8,
            /// List of sequential actions.
            actions: Vec<Action>,
        },
    }
    

    where Action is either SwapAction or any future action added there.

    opened by referencedev 1
  • Add return value to withdraw / withdraw_owner_token

    Add return value to withdraw / withdraw_owner_token

    withdraw now returns withdrawal amount on success and 0 otherwise. This way the caller will be able to take appropriate actions on withdraw fail

    withdraw_owner_token also affected in the same way

    opened by vitalii427 0
  • Broken README link

    Broken README link

    https://github.com/ref-finance/ref-contracts/blob/173cbce929a17d999c7965194bcb10b5c48deee3/README.md?plain=1#L10 link whiffs on https://docs.ref.finance/smart-contracts/ref-exchange.

    I would open a PR, but unsure what the link should be updated to. Also, since there is ref-farming contract added, unsure if that should be added, along with the other test token. Assume this might want to be updated to https://guide.ref.finance/

    opened by austinabell 0
  • [enhancement] Add SECURITY.md

    [enhancement] Add SECURITY.md

    Someone finding a bug will probably do it by looking at code on GitHub. It'd be great to also have the security process on the same repository to make it easier for them to follow the team's suggestions. For reference, yearn.finance does a great job imo by including this file which redirects to their full security process

    opened by chluff 0
  • Feature request: recipient field for swaps

    Feature request: recipient field for swaps

    Uniswap has a to field allowing the output tokens to be sent to an address other than the signer.

    https://github.com/Uniswap/v2-core/blob/4dd59067c76dea4a0e8e4bfdda41877a6b16dedc/contracts/UniswapV2Pair.sol#L159

    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data)
    

    Ref should implement this. Suppose we have a proxy contract for swaps-

    1. In EVM, we can set the the to field as the signer's address. This way the tokens directly go to the user.
    2. With Ref, the proxy contract will get the output tokens. Sending the tokens to the user will require another transfer. This more more code and higher gas fee.
    opened by secretshardul 0
  • [help] debug fail swap transaction

    [help] debug fail swap transaction

    I'm trying to make a swap from wnear -> usdt by trading bot can you tell me what wrong here ? https://explorer.mainnet.near.org/transactions/4YDCicMAY7cFLotBA2iDH2RZU7aSbBTWpo7gn9Pj5yUn

    opened by thanhnguyennguyen 0
  • Potentially required contract updates due to increased deployment cost

    Potentially required contract updates due to increased deployment cost

    Deployment costs per byte of code are going to be increased by a factor of ~5 with this change to NEAR protocol: https://github.com/near/nearcore/pull/6397 I believe this does not break any of your code but I want to raise awareness so that you can double-check before this is deployed.

    Probably this will be included with protocol version 53, which would be released on testnet by March 23 and on mainnet by April 20.

    Why am I even contacting you? To find everyone affected by this change, I listed all the indirect deployments from the past that would fail with the new cost, if all gas attachments stay the same. One deployment from v2.ref-finance.near and one from v2.ref-farming.near showed up in this list. Meaning that the mechanism used to deploy them in the past might no longer work after the new release.

    I am guessing ref-exchange is deployed on v2.ref-finance.near and ref-farming on v2.ref-farming.near, right? Both seem to follow a similar pattern for upgrades. Here is the code I found for ref-farming.

    https://github.com/ref-finance/ref-contracts/blob/2ecbe5c7897e9ad1783fb5378d17eab66bad7436/ref-farming/src/owner.rs#L57-L102

    First of all, props to you for let attached_gas = env::prepaid_gas() - env::used_gas() - GAS_FOR_MIGRATE_CALL;. Using this dynamic gas value for the following function call means that you are probably fine with the upgrade even without any changes. (Other contracts use hard-coded values and they are breaking with the increased cost.)

    What I want to tell you is that the cost to deploy ref_farming_release.wasm, or any contract of size 416KB, will go from ~6.04TGas to ~30.07Tgas. (That is pure deployment cost, without function call costs or storage costs.) After a quick scan over your code, I see nothing that would break because of this increase. But please review this for yourself.

    opened by jakmeier 2
  • get_number_of_pools misbehaving

    get_number_of_pools misbehaving

    Looking at Eugene's token factory:

    https://github.com/evgenykuzyakov/token-factory/blob/15aae092a4cae928f119140632af0512448071ae/frontend/src/Tokens.js#L343

    we run into an issue

    Error: Querying call/ref-finance.near/get_number_of_pools,AQ4 failed: wasm execution failed with error: FunctionCallError(CompilationError(PrepareError(Deserialization))).
    {
      "error": "wasm execution failed with error: FunctionCallError(CompilationError(PrepareError(Deserialization)))",
      "logs": [],
      "block_height": 59982114,
      "block_hash": "5D6urqUnTgcAxuHAqTe54qhRsffE1YS9ZUHsrvD9VuCe"
    }
        at JsonRpcProvider.query (json-rpc-provider.js:80:1)
        at async ConnectedWalletAccount.viewFunction (account.js:271:1)
        at async Tokens.refreshRefPools (Tokens.js:346:1)
        at async Promise.all (:3000/index 0)
        at async Tokens.refreshRef (Tokens.js:335:1)
    

    Running this command on NEAR CLI also throws the same error:

    NEAR_ENV=mainnet near view ref-finance.near get_number_of_pools
    
    opened by mikedotexe 1
Owner
Ref Finance
Ref Finance
Minimal Substrate node configured for smart contracts via pallet-contracts.

substrate-contracts-node This repository contains Substrate's node-template configured to include Substrate's pallet-contracts ‒ a smart contract modu

Parity Technologies 73 Dec 30, 2022
evm2near compiles Solidity contracts into NEAR WebAssembly contracts.

EVM → NEAR evm2near is a project for compiling EVM bytecode into wasm bytecode, with the particular goal of having that wasm artifact be executable on

Aurora 125 Dec 3, 2022
Ticketed Discreet Log Contracts (DLCs) to enable instant buy-in for wager-like contracts on Bitcoin.

dlctix Ticketed Discreet Log Contracts (DLCs) to enable instant buy-in for wager-like contracts on Bitcoin. This project is part of the Backdrop Build

null 7 Feb 29, 2024
Rust client to Opensea's APIs and Ethereum smart contracts

opensea.rs Rust bindings & CLI to the Opensea API and Contracts CLI Usage Run cargo r -- --help to get the top level help menu: opensea-cli 0.1.0 Choo

Georgios Konstantopoulos 226 Dec 27, 2022
A framework for creating PoC's for Solana Smart Contracts in a painless and intuitive way

Solana PoC Framework DISCLAIMER: any illegal usage of this framework is heavily discouraged. Most projects on Solana offer a more than generous bug bo

Neodyme 165 Dec 18, 2022
My code for the terra.academy course on CosmWasm smart contracts

CosmWasm Starter Pack This is a template to build smart contracts in Rust to run inside a Cosmos SDK module on all chains that enable it. To understan

Alex Incerti 0 Nov 7, 2021
Smart contracts powering Spectrum Protocol on Terra

Spectrum Core Contracts This monorepository contains the source code for the core smart contracts implementing Spectrum Protocol on the Terra blockcha

Spectrum Protocol 38 Dec 19, 2022
A template to build smart contracts in Rust to run inside a Cosmos SDK module on all chains that enable it.

CosmWasm Starter Pack This is a template to build smart contracts in Rust to run inside a Cosmos SDK module on all chains that enable it. To understan

null 1 Mar 7, 2022
Create your personal token with rust smart contracts

Solana Rust Token ?? This application written Rust using Anchor ⚓

Ritesh 6 Nov 22, 2022
This is a node implementation of Thippy, a Substrate parachain for smart contracts

Thippy ‒- A Smart Contracts Parachain This is a node implementation of Thippy, a Substrate parachain for smart contracts. Developing Smart Contracts f

Arthur·Thomas 15 Mar 16, 2022
Rust library for build smart contracts on Internet Computer, by the Spinner.Cash team.

Spinner Rust library for building smart contracts on the Internet Computer. More specifically it is used by Spinner.Cash, a decentralized layer-2 prot

Spinner 6 May 31, 2022
Rust implementation for Thippy -- a Substrate parachain for smart contracts.

Thippy ‒- A Smart Contracts Parachain This is a node implementation of Thippy, a Substrate parachain for smart contracts. Developing Smart Contracts f

Arthur·Thomas 15 Mar 16, 2022
Helpful functions and macros for developing smart contracts on NEAR Protocol.

near-contract-tools Helpful functions and macros for developing smart contracts on NEAR Protocol. This package is a collection of common tools and pat

Jacob 27 Dec 17, 2022
🖨 Template for Rust applications & smart contracts @okp4.

Rust Template Template for Rust projects @okp4. Purpose & Philosophy This repository holds the template for building Rust projects with a consistent s

OKP4 – Open Knowledge Protocol For 6 Nov 17, 2022
CLI for Stellar Smart Contracts.

stellar-contract-cli CLI for running Stellar contracts locally in a test VM. Executes WASM files built using the rs-stellar-contract-sdk. Install carg

Stellar 22 Dec 20, 2022
A gRPC-based scripting library for interacting with CosmWasm smart-contracts.

Cosmos Rust Script Smart contract scripting library to ease CosmWasm smart contract development and deployment. cosm-script is inspired by terra-rust-

null 11 Nov 3, 2022
Helpful functions and macros for developing smart contracts on NEAR Protocol.

near-contract-tools Helpful functions and macros for developing smart contracts on NEAR Protocol. This package is a collection of common tools and pat

NEARFoundation 9 Aug 3, 2022
A simple example demonstrating cross-contract calls in CosmWasm smart contracts

Cross-contract calls This tutorial demonstrates cross-contract calls with CosmWasm v1. Overview An end user calls the reservation contract to register

csli Tools 3 Sep 12, 2022
Rust client to Seaport's APIs and Ethereum smart contracts(WIP)

Seaport-rs WIP - WORK IN PROGRESS. REFER TO https://github.com/Alcibiades-Capital/quay FOR PRODUCTION READY CODE I'm new to Rust and seek to be legend

Perelyn 21 Nov 29, 2022