当前位置:网站首页>PHP application docking justswap special development kit【 JustSwap.PHP ]
PHP application docking justswap special development kit【 JustSwap.PHP ]
2020-11-06 20:27:05 【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]所创,转载请带上原文链接,感谢
边栏推荐
- C++ 数字、string和char*的转换
- C++学习——centos7上部署C++开发环境
- C++学习——一步步学会写Makefile
- C++学习——临时对象的产生与优化
- C++学习——对象的引用的用法
- C++编程经验(6):使用C++风格的类型转换
- Won the CKA + CKS certificate with the highest gold content in kubernetes in 31 days!
- C + + number, string and char * conversion
- C + + Learning -- capacity() and resize() in C + +
- C + + Learning -- about code performance optimization
猜你喜欢
-
C + + programming experience (6): using C + + style type conversion
-
Latest party and government work report ppt - Park ppt
-
在线身份证号码提取生日工具
-
Online ID number extraction birthday tool
-
️野指针?悬空指针?️ 一文带你搞懂!
-
Field pointer? Dangling pointer? This article will help you understand!
-
HCNA Routing&Switching之GVRP
-
GVRP of hcna Routing & Switching
-
Seq2Seq实现闲聊机器人
-
【闲聊机器人】seq2seq模型的原理
随机推荐
- LeetCode 91. 解码方法
- Seq2seq implements chat robot
- [chat robot] principle of seq2seq model
- Leetcode 91. Decoding method
- HCNA Routing&Switching之GVRP
- GVRP of hcna Routing & Switching
- HDU7016 Random Walk 2
- [Code+#1]Yazid 的新生舞会
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- HDU7016 Random Walk 2
- [code + 1] Yazid's freshman ball
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- Qt Creator 自动补齐变慢的解决
- HALCON 20.11:如何处理标定助手品质问题
- HALCON 20.11:标定助手使用注意事项
- Solution of QT creator's automatic replenishment slowing down
- Halcon 20.11: how to deal with the quality problem of calibration assistant
- Halcon 20.11: precautions for use of calibration assistant
- “十大科学技术问题”揭晓!|青年科学家50²论坛
- "Top ten scientific and technological issues" announced| Young scientists 50 ² forum
- 求反转链表
- Reverse linked list
- js的数据类型
- JS data type
- 记一次文件读写遇到的bug
- Remember the bug encountered in reading and writing a file
- 单例模式
- Singleton mode
- 在这个 N 多编程语言争霸的世界,C++ 究竟还有没有未来?
- In this world of N programming languages, is there a future for C + +?
- es6模板字符
- js Promise
- js 数组方法 回顾
- ES6 template characters
- js Promise
- JS array method review
- 【Golang】️走进 Go 语言️ 第一课 Hello World
- [golang] go into go language lesson 1 Hello World