SDK for Tokenlon v5
- [x] Get tradable tokens
- [x] Get pairs
- [x] Get market price
- [x] Auth & connect
- [x] Get Tokenlon rate
- [x] Get Tokenlon order
- [x] Unsubscribe all topics
- [x] Send order
- [x] Disconnect
- [x] Sign AMM order using MetaMask/WalletConnect provider
- [ ] Sign PMM order using MetaMask/WalletConnect provider
- [ ] Check order state
- [ ] Fetching history orders
- [ ] Check balances
- [ ] Check allowances
yarn
yarn test
yarn build
git clone git@github.com:consenlabs/tokenlon-v5-sdk.git
cd tokenlon-v5-sdk
yarn
yarn build
cd ../
npx create-react-app react-tokenlon-v5
cd react-tokenlon-v5
yarn add ../tokenlon-v5-sdk
var provider = new ethers.providers.Web3Provider(window.ethereum)
console.log(provider)
tokenlonClient = new TokenlonClient(provider)
const tokenList = await tokenlonClient.getTradeTokenList()
[{ symbol: 'ETH',
logo:
'https://aws-v2-cdn.token.im/app-mainnet-production/tokens/icons/eth%403x-2.png',
contractAddress: '0x0000000000000000000000000000000000000000',
decimal: 18,
precision: 4,
minTradeAmount: 1,
maxTradeAmount: 888,
opposites:
[ 'USDT',
'LON',
...
'ZRX' ],
xChainType: null,
xChainAddress: null },
{ symbol: 'USDT',
logo:
'https://aws-v2-cdn.token.im/app-mainnet-production/tokens/icons/USDT.png',
contractAddress: '0xdac17f958d2ee523a2206206994597c13d831ec7',
decimal: 6,
precision: 4,
minTradeAmount: 1700,
maxTradeAmount: 5000000,
opposites:
[ 'LON',
'ETH',
'WBTC',
'imBTC',
...
'ZRX' ],
xChainType: null,
xChainAddress: null },
{ symbol: 'LON',
logo:
'https://v2-cdn-dev.token.im/app-production/tokens/icons/LON.png',
contractAddress: '0x0000000000095413afc295d19edeb1ad7b71c952',
decimal: 18,
precision: 4,
minTradeAmount: 290,
maxTradeAmount: 20000,
opposites: [ 'ETH', 'USDT' ],
xChainType: null,
xChainAddress: null },
{ symbol: 'UNI',
logo:
'https://aws-v2-cdn.token.im/app-mainnet-production/tokens/icons/1f9840a85d5a_1600315206.png',
contractAddress: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
decimal: 18,
precision: 4,
minTradeAmount: 92,
maxTradeAmount: 20000,
opposites: [ 'ETH', 'USDT' ],
xChainType: null,
xChainAddress: null },
{ symbol: 'imBTC',
logo:
'https://aws-v2-cdn.token.im/app-mainnet-production/tokens/icons/IMBTC-TOKENLON.png',
contractAddress: '0x3212b29e33587a00fb1c83346f5dbfa69a458923',
decimal: 8,
precision: 6,
minTradeAmount: 0.037,
maxTradeAmount: 101,
opposites:
[ 'WBTC', 'USDT', 'ETH', 'BAT', 'DAI', 'LINK', 'PAX', 'TUSD', 'USDC' ],
xChainType: null,
xChainAddress: null }
...
]
const pairs = await tokenlonClient.getPairs()
;[
'1INCH_ETH',
'BAND_ETH',
'BAT_ETH',
'BAT_IMBTC',
'BAT_USDT',
'BUSD_ETH',
...'WBTC_TUSD',
'WBTC_USDC',
'WBTC_USDT',
'YFI_ETH',
'ZKS_USDT',
'ZRX_ETH',
'ZRX_USDT',
]
const marketPrice = await tokenlonClient.getMarketPrice('ETH', 'USDT')
{ marketName: 'blockcc', price: 1728.7088152701488 }
const token = await tokenlonClient.auth()
await tokenlonClient.connect(token)
const request: QuoteRequest = {
base: 'YFI',
quote: 'ETH',
side: 'SELL',
}
const standardQuote = await tokenlonClient.getRate(request)
console.log(standardQuote)
{ exchangeable: true,
base: 'YFI',
quote: 'ETH',
side: 'SELL',
amount: 0,
// sometime it would be string
rate: 18.50061677,
minAmount: null,
maxAmount: null,
message: null,
reason: null }
const request: QuoteRequest = {
base: 'ETH',
quote: 'YFI',
side: 'SELL',
amount: 2,
}
const orderResponse = await tokenlonClient.getNewOrder(request)
{
exchangeable: true,
order: {
makerAddress: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
makerAssetAmount: '107884020000000000',
makerAssetData:
'0xf47261b00000000000000000000000000bc529c00c6401aef6d220be8c6ea1667f6ad93e',
makerAssetAddress:'0xbc529c00c6401aef6d220be8c6ea1667f6ad93e',
makerFee: '0',
takerAddress: '0x41f8d14c9475444f30a80431c68cf24dc9a8369a',
takerAssetAmount: '2000000000000000000',
takerAssetData:
'0xf47261b00000000000000000000000000000000000000000000000000000000000000000',
takerAssetAddress: '0x0000000000000000000000000000000000000000',
takerFee: '0',
senderAddress: '0xdc6c91b569c98f9f6f74d90f9beff99fdaf4248b',
feeRecipientAddress: '0xb9e29984fe50602e7a619662ebed4f90d93824c7',
expirationTimeSeconds: '1612845996',
exchangeAddress: '0x080bf510fcbf18b91105470639e9561022937712',
salt:
'28070796282064017355823085703380248094808005579440193322978143236651240770200',
// maker signature here
makerWalletSignature: '1aa373........cd5e6fe',
quoteId: '22--bd4a6a50-1c07-4ccf-a507-fdde700b5380',
feeFactor: 30,
feeDetail:
{ stdFee: 30,
tokenlonFee: 30,
gasFee: 0,
refuelSendETH: 0,
refuelApprove: 0,
vendorFee: 0 },
protocol: 'AMMV1'
},
rate: 0.05394201,
timestamp: 0,
minAmount: 1,
maxAmount: 506.59046552732957,
message: null,
reason: null,
mmCode: 'V5AMM-QUOTER',
requestTime: 1612844195364,
responseTime: 1612844195423,
serialNo: 1
}
const request: QuoteRequest = {
base: 'YFI',
quote: 'ETH',
side: 'SELL',
}
tokenlonClient.getRate(
request,
// pass callback to the second parameter
async (err, topic, quote, subscription) => {
if (err) {
console.error(err)
return
}
console.log(topic)
console.log(quote)
// unsubscribe topic
await subscription.unsubscribe()
},
)
const request: QuoteRequest = {
base: 'YFI',
quote: 'ETH',
side: 'SELL',
amount: 1,
}
tokenlonClient.getNewOrder(request, async (err, topic, orderResponse, subscription) => {
if (err) {
console.error(err)
return
}
console.log(topic)
console.log(orderResponse)
await subscription.unsubscribe()
})
Unsubscribe all rate and quote topic.
tokenlonClient.unsubscribeAll()
const tx = await tokenlonClient.sendOrder(order, receiver)
const receipt = await tx.wait()
console.log(receipt)
await tokenlonClient.disconnect()
Remember to set your private key in both tokenlon-v5-sdk/.env
and MetaMask.
PRIVATE_KEY=0xce5259e4491968e5f1047ea3eb272ef2cb08e67e1af7fc5d80a40c1d03a44083
# start a hardhat forked mainnet
yarn run node
# compile tokenlon-v5-sdk package
yarn build
cd frontend
# install dependencies
yarn
# start the demo react project
yarn start
For more details, checkout the demo
import TokenlonClient from 'tokenlon-v5-sdk'
import * as ethers from 'ethers'
const init = () => {
var currentAccount = null
var tokenlonClient
const handleAccountsChanged = async accounts => {
if (accounts.length === 0) {
// MetaMask is locked or the user has not connected any accounts
console.log('Please connect to MetaMask.')
} else if (accounts[0] !== currentAccount) {
currentAccount = accounts[0]
console.log(currentAccount)
if (tokenlonClient) {
tokenlonClient.setSignerAddress(currentAccount)
console.log('update account')
const tokenList = await tokenlonClient.getTradeTokenList()
// Show all tradable tokens
console.log(tokenList)
// try to get jwt token
// would be blocked by CORS policy here
// should get access from *.tokenlon.im domain
const token = await tokenlonClient.auth()
console.log(token)
}
}
}
if (window.ethereum) {
window.ethereum
.request({ method: 'eth_requestAccounts' })
.then(handleAccountsChanged)
.catch(err => {
if (err.code === 4001) {
// EIP-1193 userRejectedRequest error
// If this happens, the user rejected the connection request.
console.log('Please connect to MetaMask.')
} else {
console.error(err)
}
})
window.ethereum.on('accountsChanged', handleAccountsChanged)
var provider = new ethers.providers.Web3Provider(window.ethereum)
console.log(provider)
tokenlonClient = new TokenlonClient(provider)
}
}
init()
If we request MetaMask to sign PMM order using the code below. There would be an error due to the standard 712 signing spec and incompatible 0x v2 executeTransaction format.
The key field signerAddress
of typed data is defined to an address
type. But 0x v2 protocol fill signerAddress
as a padded byte32
data. MetaMask and other providers would check these types before signing it.
Additionally, 0x-defined domain
lacks the chaindId
in standard 712 spec.
const domain = {
name: '0x Protocol',
version: '2',
verifyingContract: '0x' + this.zeroxExchange.address.slice(2).padStart(64, '0'),
}
const types = {
ZeroExTransaction: [
{ name: 'salt', type: 'uint256' },
{ name: 'signerAddress', type: 'address' },
{ name: 'data', type: 'bytes' },
],
}
const value = {
salt: takerTransactionSalt,
signerAddress: '0x' + zeroxOrder.takerAddress.slice(2).padStart(64, '0'),
data: ethers.utils.keccak256(fillData),
}
const sig = await signer._signTypedData(domain, types, value)
Also, appending a receiver address to executeTransactionHex before signing is also incompatible with standard 712 signing spec and other providers.
The only way mainstream providers could sign 0x-defined PMM order is to replace 712 signing with personal_sign
or eth_sign
. That would need a Tokenlon contracts update in PMM.sol
.
The example siging code is as shown below.
// append a receiver 20-bytes address to executeTransactionHex
const message = ethers.utils.arrayify(`0x${executeTransactionHex.slice(2)}${receiverAddr.slice(2)}`)
// personal_sign
const sig = await user.signMessage(message)
function _ecrecoverAddress(
bytes32 transactionHash,
bytes memory signature
)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s, address receiver) = decodeUserSignature(signature);
return ecrecover(
keccak256(
// Add prefiex for personal_sign
abi.encodePacked(
"\x19Ethereum Signed Message:\n52"
transactionHash,
receiver
)),
v, r, s
);
}