Simple Peer-to-Peer Exchange

Overview

Near Cetificate Devoloper - Demo

Simple Peer-to-Peer Exchange On NEAR

How it works?

See how p2p exchange work here.

Exploring The Code

The contract code lives in the /src/lib.rs

About Contract

(It's need to be mentioned that it is a pure dapp project, which means there is no centralized backend nor data server, all persistent information is stored and managed on NEAR chain by a contract.)

Contract Structure

Contract named: SimpleP2P. The structure of the contract include: accounts is an UnorderedMap that maps each account_id to that person's account, historys is a LookupMap that maps from tx (hashcode) to the transaction history

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct SimpleP2P {
    pub accounts: UnorderedMap<AccountId, AccountInformation>,
    pub historys: LookupMap<String, History>,
}

Struct named 'AccountInformation': Information about a user's account, including: Balance, Available, Selling Price, Trade history, Payment method, rating

#[derive(BorshDeserialize, BorshSerialize)]
pub struct AccountInformation {
    pub balance: Balance,   
    pub available: Balance, 
    pub price: Balance,

    pub history_buy: Vector<String>,
    pub history_sell: Vector<String>,
    
    pub bank_number: String,
    pub bank_name: String,

    pub vote_up: u128,
    pub vote_down: u128,
}

Struct name SellInformation: Used to display information, not to store. information of sell orders, including: Seller id, Balance, Available, Selling price, Payment method, Rating

#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct SellInformation {
    pub balance: Balance, 
    pub available: Balance,
    pub price: Balance,
    
    pub bank_number: String,
    pub bank_name: String,

    pub vote_up: u128,
    pub vote_down: u128,
}

Struct named History: History of transactions, including: buyer/seller id, price(in dollars), amount, value(in dollars), state of the transaction

#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct History {
    pub buyer: AccountId, 
    pub seller: AccountId,  
    pub amount: Balance,    
    pub price: Balance,
    pub value: Balance,
    pub state: String,      // init, processing, cancel, success,
}

Implement contract

#[near_bindgen]
impl SimpleP2P {
    #[init]
    pub fn new()->Self{}

    // create and deposit money
    #[payable]
    pub fn deposit(&mut self){}

    // withdraw money to near testnet wallet
    pub fn withdraw(&mut self, amount: u128){}

    // set bank number and bank name as payment method
    pub fn set_bank_account(&mut self, number: String, bank_name: String){}

    // place order sell
    pub fn order_sell(&mut self, amount: u128, price: u128){}

    // place order buy
    pub fn order_buy(&mut self, seller_id:AccountId, amount: u128){}

    // Buyer confirms that money has been sent 
    pub fn confirm_sent(&mut self, tx:String){}

    // Seller confirms receipt of the funds and the transaction is done 
    pub fn confirm_received(&mut self, tx: String){}

    // Buyer cancels buy order 
    pub fn cancel_order_buy(&mut self, tx:String){}

    // Seller cancels sell order 
    pub fn cancel_order_sell(&mut self){}

    // Vote for seller 
    pub fn vote(&mut self, account_id:AccountId, value: i8){}

    // show all accounts with sell orders 
    pub fn get_order_sell(&self)->Vec
   {}

    
   // get information of user
    
   pub 
   fn 
   get_account(
   &
   self, account_id: AccountId)->SellInformation{}

    
   pub 
   fn 
   get_transaction(
   &
   self, tx: 
   &
   String)->History{}

    
   // Get buy history of a account
    
   pub 
   fn 
   get_history_buy(
   &
   self, account_id: AccountId)->
   Vec
   
    {}

    
    // Get sell history of a account
    
    pub 
    fn 
    get_history_sell(
    &
    self, account_id: AccountId)->
    Vec
    
     {}
    
    
     // get hash code for transaction
    
     fn 
     compute_hash
     
      (buyer:
      &
      String, seller:
      &
      String, amount:
      &Balance->
      String{}
}

     
    
   
  

Get Started

Note before calling method from an account, log in with the command

near login

Preparation

I created 3 accounts: deploy.p2pexchange.testnet for contract deployment, seller1.testnet for seller account and buyer1.testnet for buyer account.

I created sub account deploy.p2pexchange.testnet for deploy contract, with command

near create-account deploy.p2pexchange.testnet --masterAccount p2pexchange.testnet

Setting environment

I have created 3 files call.sh (call from contract creator), sellercall.sh (call from seller), buyercall.sh (call from buyer), which uses the variables DEPLOY_ID, SELLER_ID and BUYER_ID.

Use the following commands to create the above variables

export DEPLOY_ID=deploy.p2pexchange.testnet
export BUYER_ID=buyer1.testnet
export SELLER_ID=seller1.testnet

Deploy contract

./build.sh
./deploy.sh

Initialize the contract

./call.sh new '{}'	

Prepare seller and buyer account

To be able to place a sell order, the seller must have a balance in the account and add a payment method

Create and deposit a amount of money into the seller's account

./sellercall.sh deposit '{}' --amount 10

Seller set payment method, This will be the method for the buyer to proceed with the payment, so please check it is correct

./sellercall.sh set_bank_account '{"number":"123456789", "bank_name":"MB Bank"}'

Create account for buyer (have to deposit some Near)

./buyercall.sh deposit '{}' --amount 1

Example

First, the seller places a sell order

./sellercall.sh order_sell '{"amount": 10, "price":2}'

Buyer check information about available sell orders

./buyercall.sh get_order_sell '{}'

Buyer places a buy order

./buyercall.sh order_buy '{"seller_id":"seller1.testnet", "amount":5}'

When a buyer places a buy order, the seller's funds are held in the p2pexchange contract.

After that, the buyer relies on the seller's payment method to proceed with the payment. After payment has been made to the seller, buyer confirm sent

./buyercall.sh confirm_sent '{"tx": "something"}'

when received the money, Seller confirm received money

./sellercall.sh confirm_received '{"tx":"something"}'

When both buyer and seller confirm send and receive money successfully, the seller's money held in the contract will be released to the buyer, the transaction ends.

View transaction status

./buyercall.sh get_transaction '{"tx":"something"}'

Rating for seller

./buyercall.sh vote '{"account_id":"seller1.testnet", "value":1}'

Check account information

./call.sh get_account '{"account_id":"seller1.testnet"}'
./call.sh get_account '{"account_id":"buyer1.testnet"}'

The seller cancels the sell order and withdraws the money to his account

./sellercall.sh cancel_order_sell '{}'
./sellercall.sh withdraw '{"amount":5}'

The buyer withdraw the money to his account

./buyercall.sh withdraw '{"amount":5}'

Troubleshooting

On Windows, if you're seeing an error containing EPERM it may be related to spaces in your path. Please see this issue for more details.

You might also like...
A simple message based networking library for the bevy framework

Spicy Networking for Bevy bevy_spicy_networking is a solution to the "How do I connect multiple clients to a single server" problem in your bevy games

Jyoti - A simple IRC bot for use with shell scripts

Jyoti - A simple IRC bot for use with shell scripts Zero dependencies. Simple usage. Hackable. Usage The idea is that Jyoti can be repurposed easily w

Simple utility to ping a TCP port.

TcpPing Simple utility to ping a TCP port. Example tcpping 1.1.1.1 53 -b en0 -i 1 -t 4 Connected to 1.1.1.1:53 in 21 ms Connected to 1.1.1.1:53 in 3

Simple in-network file transfer with barely any overhead.

fftp fftp is the "Fast File Transport Protocol". It transfers files quickly between computers on a network with low overhead. Motivation FTP uses two

A simple tcp server that written in rustlang
A simple tcp server that written in rustlang

rust_tcp A simple tcp server that written in rustlang How to build In the root dir cargo run Then you can do a test by using telnet as a client telne

Simple and fast layer 4 proxy in Rust

Fourth 这一波在第四层。 English Fourth是一个Rust实现的Layer 4代理,用于监听指定端口TCP流量,并根据规则转发到指定目标。 功能 监听指定端口代理到本地或远端指定端口 监听指定端口,通过TLS ClientHello消息中的SNI进行分流 安装方法 为了确保获得您架构

Modrinth API is a simple library for using Modrinth's API in Rust projects

Ferinth is a simple library for using the Modrinth API in Rust projects. It uses reqwest as its HTTP(S) client and deserialises responses to typed structs using serde.

Simple project to test grpc between ruby (client) and rust (server)

grpc-example Simple project to test grpc between ruby (client) and rust (server). Usage To simplify a lot this project uses docker and docker compose

Hotwire allows you to study network traffic of a few popular protocols in a simple way
Hotwire allows you to study network traffic of a few popular protocols in a simple way

Hotwire Hotwire is a gtk GUI application that leverages the wireshark and tshark infrastructure to capture traffic and explore the contents of tcpdump

Owner
null
IDP2P is a peer-to-peer identity protocol which enables a controller to create, manage and share its own proofs as well as did documents

IDP2P Experimental, inspired by ipfs, did:peer and keri Background See also (related topics): Decentralized Identifiers (DIDs) Verifiable Credentials

null 5 Oct 31, 2022
Peer-to-peer communications library for Rust based on QUIC protocol

qp2p Crate Documentation MaidSafe website SAFE Dev Forum SAFE Network Forum Overview This library provides an API to simplify common tasks when creati

MaidSafe 337 Dec 14, 2022
Easy-to-use wrapper for WebRTC DataChannels peer-to-peer connections written in Rust and compiling to WASM.

Easy-to-use wrapper for WebRTC DataChannels peer-to-peer connections written in Rust and compiling to WASM.

null 58 Dec 11, 2022
Peer-to-peer overlay routing

Rust_Pinecone This is a port of the peer-to-peer overlay routing mechanism Pinecone and aims to be interoperable with it, although it isn't yet becaus

null 3 Aug 2, 2022
Mateversum is a peer-to-peer WebXR metaverse project.

Mateversum ?? Mateversum (pronounced: MAH-tay-ver-sum) is a peer-to-peer WebXR metaverse project. The idea is that you'd be able to connect to a netwo

Ashley 23 Dec 21, 2022
Quick Peer-To-Peer UDP file transfer

qft QFT is a small application for Quick (and really reliable) Peer-To-Peer UDP file transfer. If a friend sent you here... ...look at the "Releases"

Daniel H. 99 Jan 7, 2023
Core library for Lightning Network peer-to-peer nostr platform

Mostro server This document explains how Mostro works. Overview Due to the growing need to be able to operate with Bitcoin without giving up personal

Mostro 16 Jan 4, 2023
A tcp proxy server/client which exchange the data in temp files

ftcp A tcp proxy server/client which exchange the data in temp files 通过在临时文件中交换数据来进行TCP代理的一个服务端/客户端 学校内网中有针对教学楼的防火墙导致教室电脑难以上网( 但学校内建有公共ftp服务器,因此就有了这个借

Daile Liu 2 Feb 17, 2022
BitTorrent peer ID registry/parser/(soon) encoder for Rust

BitTorrent peer ID registry/parser/(soon) encoder By convention, BitTorrent clients identify themselves and their versions in peer IDs they send to tr

TORRENTDYNE 3 Oct 16, 2023
Simple VPN implemented using rust

fubuki Simple VPN implemented using rust fubuki是类似与tincVPN的简单组网工具 不支持对等NAT 支持的平台: Windows Linux 工作机制 它由一台拥有公网IP的服务器来维持各个内网客户端的实际地址映射,在客户端和客户端之间实现P2P通信

XTY 84 Dec 31, 2022