当前位置:网站首页>PHP application docking justswap special development kit【 JustSwap.PHP ]
PHP application docking justswap special development kit【 JustSwap.PHP ]
2020-11-06 20:27:00 【Blockchain tutorial】
JustSwap.php The development package is suitable for PHP The application increases rapidly to JustSwap The support capability of the protocol . It supports the use of own deployment Tron Application scenarios of blockchain nodes , Lightweight deployment scenarios using third-party nodes are also supported , Official download address :JustSwap docking PHP Development kit .
1、 Development package Overview
JustSwap.php The development package mainly includes the following features :
- One key deployment JustSwap agreement , Facilitate rapid development and testing
- Support JustSwap All interfaces to the protocol , And provide developer friendly API
- Support TRX/TRC20 The creation of liquidity 、 Add and remove
- Support TRX/TRC20、TRC20/TRX、TRC20/TRC20 The exchange transaction of the trading pair
- Support automatic market making price calculation and sliding point calculation
JustSwap.php The development package runs in Php 7.1+ In the environment , current version 1.0.0, Main categories / The interface and relationship are shown in the figure below :
JustSwap.php For a list of the main code files of the development package, see Website shows .
2、 Use sample code
2.1 Compile contract
Enter the project directory at the terminal , Execute the following command to compile the JustSwap Protocol and testing Token contract :
~$ cd ~/justswap.php
~/justswap.php$ ./bin/build-contracts
The results are as follows :
2.2 Deployment contract
Entry project demo Catalog , Execute the following command to deploy the contract :
~/justswap.php/demo$ php deploy-contracts.php
The above command will deploy the complete JustSwap Protocol and testing HubToken And WizToken, Record the contract deployment address in the project demo In the catalog addresses.json In file .
The execution results of the contract deployment script are as follows :
Be careful : You need to set up demo/config.php Deployment account in .
2.3 Create flow pools
Code create-exchange.php
Demonstrates how to create TRX/TRC20 Mobile pool .
Enter the project at the terminal demo Catalog , Execute the following command :
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php create-exchange.php
The results are as follows :
2.4 Token to grant authorization
Code approve-token.php
Demonstrates how to authorize justswap Exchange The contract agent operates the current account HUB token and WIZ token.
Enter the project at the terminal demo Catalog , Execute the following command :
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php approve-token.php
The results are as follows :
2.5 Add liquidity
Code add-liquidity.php
Demonstrates how to add liquidity to the flow cell .
Enter the project at the terminal demo Catalog , Execute the following command to Hub token Add liquidity :
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php add-liquidity.php hub
If it is the first execution after the flow pool is created php add-liuqidity.php hub
, So for TRX/HUB The pool will add initial liquidity and will determine the initial conversion ratio (10 TRX/10 HUB). The results are as follows :
If it is a flow pool, it will be executed after the initial liquidity already exists php add-liquidity.php hub
, Then according to TRX/HUB The current conversion ratio adds liquidity , The results are as follows :
In the same way TRX/WIZ The pool adds initial liquidity (10 TRX/10 WIZ):
~/justswap.php/demo$ php add-liquidity.php wiz
The results are as follows :
2.6 Remove liquidity
Code remove-liquidity.php
Demonstrates how to remove liquidity from a specified flow cell . You can use parameters hub or wiz Specify the pool to remove liquidity from .
Enter the project at the terminal demo Catalog , Execute the following command from TRX/HUB The pool overflows 25% Mobility :
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php remove-liquidity.php hub
The results are as follows :
2.7 TRX/TRC20 exchange : To input TRX Quantity as the basis
Code swap-exact-trx-for-tokens.php
Demonstrate and how to put a specified number of TRX Exchange for TRC20 token. You can use parameters hub or wiz Designated to be exchanged token.
Enter the project at the terminal demo Catalog , Executing the following command will 0.1 TRX Exchange for the corresponding amount of HubToken:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-exact-trx-for-tokens.php hub
The results are as follows :
2.8 TRX/TRC20 exchange : To output token Quantity as the basis
Code swap-trx-for-exact-tokens.php
Demonstrates how to put TRX Exchange for a specified amount of TRC20 token. You can use parameters hub or wiz Designated to be exchanged token.
Enter the project at the terminal demo Catalog , Execute the following command with TRX Exchange it back 0.1 HUB:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-trx-for-exact-tokens.php hub
The results are as follows :
2.9 TRC20/TRX exchange : To input token Quantity as the basis
Code swap-exact-tokens-for-trx.php
Demonstrates how to add a specified number of TRC20 token Exchange for TRX. You can use parameters hub or wiz Designated to be exchanged token.
Enter the project at the terminal demo Catalog , Executing the following command will 1 HUB Exchange for the corresponding amount of TRX:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-exact-tokens-for-trx.php hub
The results are as follows :
2.10 TRC20/TRX exchange : To output TRX Quantity as the basis
Code swap-tokens-for-exact-trx.php
Demonstrates how to put ERC20token Exchange for a specified amount of ETH. You can use parameters hub or wiz Designated to be exchanged token.
Enter the project at the terminal demo Catalog , Execute the following command with HUB Exchange it back 1 TRX:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-tokens-for-exact-trx.php hub
The results are as follows :
2.11 TRC20/TRC20 exchange : To input token Quantity as the basis
Code swap-exact-tokens-for-tokens.php
Demonstrates how to implement to input token Quantity based TRC20/TRC20 exchange .
Enter the project at the terminal demo Catalog , Executing the following command will 1 HUB Exchange for the corresponding amount of WIZ:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-exact-tokens-for-tokens.php
The results are as follows :
2.12 TRC20/TRC20 exchange : To output token Quantity as the basis
Code swap-tokens-for-exact-tokens.php
Demonstrates how to implement to output token Quantity based TRC20/TRC20 exchange .
Enter the project at the terminal demo Catalog , Execute the following command with HUB Exchange it back 1 WIZ:
~$ cd ~/justswap.php/demo
~/justswap.php/demo$ php swap-tokens-for-exact-tokens.php
The results are as follows :
3、 Use justswap.php Development kit
SwapKit It's the entry point to the development package , Use SwapKit Class can quickly implement the following functions :
- Liquidity management : Support TRX/TRC20 The creation of the flow cell 、 Add and delete
- The creation and execution of exchange transactions : Support TRC20/TRC20、TRC20/TRX、TRX/TRC20 And all kinds of deals , Support to input or output prices based on
- User location query : Query the position of the designated account in the designated trading pair , For example, the number of positions 、 Proportion, etc .
3.1 Instantiation SwapKit
SwapKit Instantiation requires passing in three parameters :
- TronApi example
- Used to perform contract interactions Tron Identity certificate object , That is, a
Credential
object - JustSwap Agreed factory contract address
for example , The following code creates an access Tron Main network justswap Agreed SwapKit example :
//use JustSwap\TronApi;
//use JustSwap\Credential;
//use JustSwap\SwapKit;
$kit = new SwapKit(
TronApi::mainNet(), //Tron Main network
Credential::fromPrivateKey('4f3e...3b1d'), // Default execution account , Specify private key
'TXk8rQSAvPvBBNtqSoY6nCfsXWCSSpTVQF', //justswap Factory contract address
);
3.2 Credential:Tron Identity and address indicate
stay justswap.php In the development package , Use Credential characterization Tron A user identity in the blockchain , Compared with the address ,Credential The object contains the private key information of the user , Can be used to sign transactions , So we need to protect it from leakage .
Use Credential Class static methods create()
Create a new account . for example , The following code creates a new account and displays its private key 、 Public key and address :
//use JustSwap\Credential;
$alice = Credential::create(); // Create a new account
echo 'private key => ' . $alice->privateKey() . PHP_EOL; // Show private key
echo 'public key => ' . $alice->publicKey() . PHP_EOL; // Show public key
echo 'address => ' . $alice->address()->base58() . PHP_EOL; // display address
You can use static methods fromPrivateKey()
Import an existing private key to instantiate Credential. For example, the following code imports an existing private key and displays the address :
//use JustSwap\Credential;
$alice = Credential::fromPrivateKey('7889...023a'); // Import the existing private key
echo 'address => ' . $alice->address()->base58() . PHP_EOL; // Display the corresponding address
3.3 Create flow pools
Use JustSwap Factory example createExchange()
Method to create a flow pool , for example :
$tokenAddr='TRbojfoxNQ2HcJPM85rY5N34aQFafEXZMA'; // Token address
$txid = $kit->getFactory()->createExchange($tokenAddr, []);
echo 'txid => ' . $txid . PHP_EOL;
3.4 Generate liquidity add / Remove the order
because justswap The agreement involves transaction sliding point processing and price pre calculation , therefore justswap.php Provides a specialized class OrderBuilder Used to generate liquidity additions / Remove the order .OrderBuilder Automatic price calculation and sliding point calculation are built in , Therefore, the caller only needs to specify the basic data to generate and submit to justswap The liquidity of the contract adds / Remove the order .
Use SwapKit Object's getOrderBuilder()
Method to get the pre created OrderBuilder object , And call OrderBuilder Of build()
Method to generate a delegation order . for example :
$order = $kit->getOrderBuilder() // return OrderBuilder object
->.... // Parameter setting
->build(); // Generate and return the order
OrderBuilder Object provides the following methods to adjust the behavior of the generator :
- orderType($type) : Set delegation type , There are currently two kinds of :
Order::LIQUIDITY_ADD
- Liquidity add ordersOrder::LIQUIDITY_REMOVE
- Liquidity removal orders
- tokenA($addr) / tokenB($addr) : Two of the trading pairs Token Address . Use special
SwapKit::TRX_TOKEN
Express TRX, And right justswap Agreement for tokenA Must be set to TRX, namelySwapKit::TRX_TOKEN
- amountA($bn) / amountB($bn) : Two token The added quantity of , You need to set... Only when adding flows
- liquidity($bn) :LP token Number , Only need to set when removing liquidity
- slippage($bn) : Trading slider settings , The default value is 5, Express 0.5% The sliding point tolerance interval of
for example , The following code generates a liquidity add order :
use justswap\Order;
$order = $kit->getOrderBuilder() // Get the delegate generator object
->orderType(Order::LIQUIDITY_ADD) // Add liquidity
->tokenA(SwapKit::TRX_TOKEN) // The deal is right TokenA, It has to be for TRX
->tokenB('0x...') // The deal is right TokenB
->amountA(bn('100000000000000000000')) // With TokenA Based on the quantity, it is calculated automatically according to the market price TokenB Number
->slippage(bn('10')) // Slip point tolerance range 1%
->build(); // Generate a delegation order
echo 'amountA => ' . $order->amountA . PHP_EOL; //TokenA Set the number
echo 'amountB => ' . $order->amountB . PHP_EOL; //TokenB Count the quantity
echo 'amountAMin => ' . $order->amountAMin . PHP_EOL; // After sliding point treatment TokenA Minimum acceptable quantity
echo 'amountBMin => ' . $order->amountAMin . PHP_EOL; // After sliding point treatment TokenB Minimum acceptable quantity
Be careful :
- Use special SwapKit::TRX_TOKEN In the middle of a transaction TRX, The value is :
T9yD14Nj9j7xAB4dbGeiX9h8vMa2GfnLve
bn($numstr)
yes justswap A creation provided BigInteger object The shortcut function of , Its parameter is 10 Base string .- token The quantity is specified in the smallest unit
Allied , The following code generates a liquidity removal order :
$order = $kit->getOrderBuilder() // Get the delegate generator object
->orderType(Order::LIQUIDITY_REMOVE) // Remove liquidity
->tokenA('0x...') // The deal is right TokenA Address
->tokenB('0x...') // The deal is right TokenB Address
->liquidity(bn('10000000000000000000')) // The amount of liquidity to be removed
->slippage(bn('10')) // Slip point tolerance range 1%
->build(); // Generate a delegation order
echo 'amountAMin => ' . $order->amountAMin . PHP_EOL; // At least the sliding point should be received TokenA Number
echo 'amountBMin => ' . $order->amountAMin . PHP_EOL; // At least the sliding point should be received TokenB Number
Order Object provides the following values , Helps to provide better feedback to users before executing the order :
- amountA/amountB : Market price calculation tokenA or tokenB Ideal value
- amountAMin/amountAMax : After sliding point treatment tokenA minimum value / Maximum
- amountBMin/amountBMax : After sliding point treatment tokenB minimum value / Maximum
3.5 Execute liquidity orders
Use SwapKit Of executeOrder() Method to execute the generated liquidity order , Finally, liquidity is added / Remove the transaction . for example :
$txid = $kit->executeOrder($trade); // Execute the order
echo 'txid => ' . $txid . PHP_EOL; // Show transactions ID
have access to SwapKit Object's waitForConfirmation()
Method to wait for transaction confirmation , This method returns after the transaction is confirmed true or false, The transaction is successfully executed or the transaction is rolled back .
for example :
$success = $kit->waitForConfirmation($txid);
echo 'success => ' . $success . PHP_EOL;
3.6 Query position information
Use SwapKit Of getExchangeLiquidityInfoForToken() Method can query the specified account in the specified token Position information of the flow pool . For example, inquire about the position of a certain address :
$info = $kit->getExchangeLiquidityInfoForToken( // Query position information
$kit->getCredential()->address()->base58(), // Current account
'TENh4XGvTPEdceEVxiXoEfH9ufxyjYrSwn' //token Address
);
echo 'total => ' . $info->totalSupply . PHP_EOL; //LP Total amount
echo 'balance => ' . $info->balance . PHP_EOL; // Number of positions held
echo 'share % => ' . $info->share . PHP_EOL; // Position ratio
3.7 Generate exchange trading object
Similar to the addition and removal of liquidity , stay justswap There are also problems of automatic price calculation and sliding point processing in the exchange of transaction pairs in . So ,justswap.php The development package provides a specialized class TradeBuilder To simplify this operation .TradeBuilder Built in price automatic calculation and sliding point processing , Therefore, the caller only needs to set the basic parameters .
Use SwapKit Object's getTradeBuilder()
Method to get the pre created TradeBuilder object , for example :
$tb = $kit->getTradeBuilder() // Get the pre created exchange transaction generator
->... // Parameter setting
->build(); // Generate exchange trading object
TradeBuilder Provides the following methods to adjust the behavior of the generator :
- tradeType($type) : Exchange type , Optional value is :
Trade::EXACT_INPUT
- With tokenIn Based on the number ofTrade::EXACT_OUTPUT
- With tokenOut Based on the number of
- tokenIn($addr) - Input Token The address of
- tokenOut($addr) - Output Token The address of
- amountIn($bn) - Input quantity , Only if the exchange type is
EXACT_INPUT
You need to set - amountOut($bn) - Output quantity , Only if the exchange type is
EXACT_OUTPUT
You need to set - slippage($bn) - Trading slider settings , The default value is 5, It means to allow 0.5% The sliding point of
- to($addr) - Output token Receiving address
for example , The following code is used to enter token Quantity as the benchmark to generate an exchange trading object :
$trade = $kit->getTradeBuilder() // Get exchange transaction generator
->tradeType(Trade::EXACT_INPUT) // To input token Quantity as the basis
->tokenIn('0x...') // Input token
->tokenOut('0x...') // Output token
->amountIn(bn('10000000000000000000')) // Input token The number of
->slippage(bn('10')) // Slip point tolerance range 1%
->to($kit->getDefaultAddress()) // Output token Receiving address of
->build(); // Generate exchange trading object
echo 'amountIn => ' . $trade->amountIn . PHP_EOL; // Input token Number of settings for
echo 'amountOut => ' . $trade->amountOut . PHP_EOL; // The output from the automatic market making algorithm token The number of
echo 'amountOutMin => ' . $trade->amountOutMin . PHP_EOL; // The output that should be received after sliding point processing token Minimum quantity
3.8 Execute the exchange transaction
Use SwapKit Object's executeTrade() Method to execute the specified exchange trading object . for example :
$txid = $kit->executeTrade($trade); // Execute the exchange transaction
echo 'txid => ' . $txid . PHP_EOL; // Show transactions ID
have access to SwapKit Object's waitForConfirmation()
Method to wait for transaction confirmation , This method returns after the transaction is confirmed true or false, The transaction is successfully executed or the transaction is rolled back .
for example :
$success = $kit->waitForConfirmation($txid);
echo 'success => ' . $success . PHP_EOL;
JustSwap.php Official download address :http://sc.hubwiz.com/codebag/justswap-php/
版权声明
本文为[Blockchain tutorial]所创,转载请带上原文链接,感谢
边栏推荐
- What if the front end doesn't use spa? - Hacker News
- Azure data factory (3) integrate azure Devops to realize CI / CD
- It's time for your financial report to change to a more advanced style -- financial analysis cockpit
- Simple summary of front end modularization
- What are Devops
- html+vue.js 實現分頁可相容IE
- 大道至简 html + js 实现最朴实的小游戏俄罗斯方块
- 零基础打造一款属于自己的网页搜索引擎
- 一篇文章教会你使用Python网络爬虫下载酷狗音乐
- Analysis of query intention recognition
猜你喜欢
What to do if you are squeezed by old programmers? I don't want to quit
【转发】查看lua中userdata的方法
How to turn data into assets? Attracting data scientists
What are manufacturing and new automation technologies?
Markdown tricks
只有1个字节的文件实际占用多少磁盘空间
一路踩坑,被迫聊聊 C# 代码调试技巧和远程调试
Behind the record breaking Q2 revenue of Alibaba cloud, the cloud opening mode is reshaping
What are Devops
每个大火的“线上狼人杀”平台,都离不开这个新功能
随机推荐
Analysis of ThreadLocal principle
Azure data factory (3) integrate azure Devops to realize CI / CD
Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?
視覺滾動[反差美]
The AI method put forward by China has more and more influence. Tianda et al. Mined the development law of AI from a large number of literatures
【自学unity2d传奇游戏开发】地图编辑器
零基础打造一款属于自己的网页搜索引擎
Basic principle and application of iptables
What are the common problems of DTU connection
Introduction to Google software testing
Python saves the list data
事件监听问题
消息队列(MessageQueue)-分析
Analysis of partial source codes of qthread
快速排序为什么这么快?
Live broadcast preview | micro service architecture Learning Series live broadcast phase 3
[Xinge education] poor learning host computer series -- building step 7 Simulation Environment
Swagger 3.0 brushes the screen every day. Does it really smell good?
How to get started with new HTML5 (2)
[actual combat of flutter] pubspec.yaml Configuration file details