@zecrey/zecrey-mobile-core-l2
v0.1.42
Published
## Account information
Downloads
51
Readme
zecrey-mobile-core-l2
Account information
let zecrey_keypair = account.keypairs.find((i) => i.type === "Zecrey");
let { publicKey, name } = zecrey_keypair;
let url = "https://..."; // L2 API base url
let enc_url = "https://..."; // decrypt L2 number API base url
1. Register Zecrey L2 account with a keypair and a name.
import { registerL2Account } from "@zecrey/zecrey-mobile-core-l2";
try {
let name = "example.zecrey";
await registerL2Account(name, publicKey, url);
} catch (err) {
throw err;
// It fails if the name is already taken, with an error message like "example.zecrey already registered".
}
2. Get Zecrey L2 account information by public key.
import { fetchAccountDetailByPublicKey } from "@zecrey/zecrey-mobile-core-l2";
let { accountName, accountIndex } = await fetchAccountDetailByPublicKey(
publicKey,
url
);
// It only works for active accounts, those registered and deposited assets already.
// It throws an error if there's no active account with the given key.
3. Get Zecrey L2 account status.
import { getL2AccountStatus } from "@zecrey/zecrey-mobile-core-l2";
let { isRegistered, isActive, accountName } = await getL2AccountStatus(
publicKey,
url
);
// It works for all accounts, including unregistered ones, registered but inactive ones, and active ones.
4. Get Zecrey L2 account index by name.
import { getAccountIndexByName } from "@zecrey/zecrey-mobile-core-l2";
let accountIndex = await getAccountIndexByName("example.zecrey", url); // 65326
// Use it to check on the payee account for L2-transfer.
// It throws an error if there's no account registered with the given name.
5. Get account's locked assets
import {
CHAIN_ID_USED_IN_L2,
getLockedAssetByAccountIndex,
} from "@zecrey/zecrey-mobile-core-l2";
// Get all the locked amounts of all assets of each chain of the given account.
let locked = await getLockedAssetByAccountIndex(accountIndex, url);
// Get the locked amount of asset REY from Ethereum.
let ETHEREUM_ID = CHAIN_ID_USED_IN_L2["Ethereum"];
let REY_ID = 0;
let amount = locked[ETHEREUM_ID][REY_ID]; // number without decimal
// Please remember to correct the numbers calculated with their decimal places.
6. Get account's liquidity information
import {
getLpByAccount,
L2AssetController,
} from "@zecrey/zecrey-mobile-core-l2";
let controller = new L2AssetController(...args, () => url);
let assets = controller.getAssets(); // information of all the L2 assets
// Get the information of all the liquidity the user added
let LPs = await getLpByAccount(accountIndex, asstes, url);
// Get the balance of one of the liquidity the user added
let bal = await getLpByAccountAndPairIndex(accountIndex, pairIndex, url); // decrypted balance string
// Get the total lp amount and total assets amount of the pair.
let info = await getPairInfo(pairIndex, url); // {asset_a_amount: 20657355, asset_b_amount: 12673266, total_lp_amount: 16180116}
7. Get account's L2 assets' information (balance encrypted)
import { getL2AssetListByAccountIndex } from "@zecrey/zecrey-mobile-core-l2";
let assets = await getL2AssetListByAccountIndex(accountIndex, url); // without decrypted balance
// Please decrypt the encrypted balance strings with DecryptManager to get balances in number.
Decrypt L2 number
All the asset amounts in Layer 2 are encrypted. Decrypt with the user's private key to get the amount in number.
import { DecryptManager } from "@zecrey/zecrey-mobile-core-l2";
// eg.
// 1. A proper way to decrypt an encrypted private key to hex string.
let getDecryptPrivateKey = async (encryptedPrivateKey) => {
// ...
return Promise.resolve("..."); // the decrypted private key of the Zecrey keypair
};
// 2. Proper ways to get the permitted accounts' information.
// Please check on the user permission/access before decrypting.
let getAllAccounts = () => store.accounts;
let getCurrentAccount = () => store.currentAccount;
// 3. 'elgamalRawDec' method from the crypto lib.
let elgamalRawDec = global.elgamalRawDec;
// 4. Instance
let manager = new DecryptManager(
getDecryptPrivateKey,
getAllAccounts,
getCurrentAccount,
elgamalRawDec,
() => enc_url
);
// 5. Decrypt.
// Decrypt with the current account.
let num1 = await manager.decrypt([
{
enc: "I9dK8ZfIf0YQ/kn/lr9tMnSyK0eEA2/5iGxZDytkMK8vNgCJQ1Zh0LojHwVRBS5Oq5SUNMRKW6EfTpYVgRregA==",
decimal: 4,
},
]); // [24.3954]
// Decrypt with a selected account of the current wallet.
let num2 = await manager.decrypt(
[
{
enc: "I9dK8ZfIf0YQ/kn/lr9tMnSyK0eEA2/5iGxZDytkMK8vNgCJQ1Zh0LojHwVRBS5Oq5SUNMRKW6EfTpYVgRregA==",
decimal: 4,
},
],
"Account 1", // name of the account, whose private key is used to decrypt the balance_enc strings.
enc_url // optional
);
// 6. It works as well if the enc string isn't an encrypted string.
let num3 = await manager.decrypt([{ enc: "100", decimal: 0 }]); // [100]
L2 Asset Controller
import { DecryptManager, L2AssetController } from "@zecrey/zecrey-mobile-core-l2";
// 1. A proper way to get the current account's information.
let getCurrentAccount = () => store.currentAccount;
// 2. A proper way to decrypt L2 numbers.
let decryptManager = new DecryptManager(...);
let decrypt = decryptManager.decrypt;
// 3. A proper way to get the token price, using local cache or HTML requests.
let getPrice = store.PriceTracker.getPrice;
// 4. Instance
let controller = new L2AssetController(
getCurrentAccount, decrypt, getPrice, () => url
);
// 5. Fetch or update balance of L2 assets. Please refresh when new transaction's published or account changes.
controller.fetch();
// 6. Get total asset value of the current account.
let total = controller.getTotal(); // "600.00", in USD
// 7. Get total asset value from one of the user's account.
let { privateKey } = zecrey_keypair;
let total = controller.getAssetMapByPrivateKey(privateKey).total; // "600.00", in USD
// 8. Get assets' information of the current account.
let assets = controller.getAssets();
// OR
let assets = controller.assets; // observable
// 9. Get assets' information from one of the user's account.
let { privateKey } = zecrey_keypair;
let assets = controller.getAssetMapByPrivateKey(privateKey).assets;
L2 transaction manager
It works for both internal and external L2 transaction request, and requires to valdiate the permission in both situations. For internal transactions, please make sure the user has unlocked the app and signs with the current selected account's keypair. For external ones, besides things mentioned above, please make sure the request is from a connected Dapp as well.
1. Instance.
import { DecryptManager, L2TxManager } from "@zecrey/zecrey-mobile-core-l2";
// 1. A proper way to get the Ethereum addresses of the permitted accounts, using PermissionsController, mobx store, local storage or something else.
let getPermittedAccounts = (origin) => {
// ...
return permitted; // ["0x09E45d6FcF322c4D93E6aFE7076601FF10BA942E"]
};
// 2. A proper way to get the current account's information.
let getCurrentAccount = () => store.currentAccount;
// 3. A proper way to decrypt L2 numbers.
let decryptManager = new DecryptManager(...);
let decrypt = decryptManager.decrypt;
// 4. A proper way to get current network.
let getNetwork = () => store.network;
// 5. Instance.
let txManager = new L2TxManager(
getPermittedAccounts, getCurrentAccount, decrypt, getNetwork, () => url
);
// Reset and refresh when the current account changes.
txManager.L2TransactionTracker.reset();
await txManager.L2TransactionTracker.refresh();
The instance of L2TxManager will fetch the latest 50 transactions automatically when it initializes. Meanwhile, it'll refresh its transaction list when any new transaction is created after its initialization.
2. Get information of published transactions
// Get transaction details by hash. It only works for transactions send by the current account.
let tx = await txManager.getTxByHash("4d3bcfa3-c3ca-11ec-8a97-42010a940002");
// Get published transaction list of the current account.
// Note: Only contains the latest 50 transactions and newly created transaction after its initialization.
let txs = txManager.getTxs();
// OR
let txs = txManager.L2TransactionTracker.transactions; // observable
// Get transactions by chain ID.
let txsByChainId = txManager.getTxs(chainId);
// Get the number of the transactions sent by the current account.
let total = txManager.L2TransactionTracker.total; // all txs
let pending = txManager.L2TransactionTracker.countPending; // pending txs
// Fetch more transactions.
// Note: the situation here is to fetch the older transactions and add to the bottom of the list.
txManager.L2TransactionTracker.fetchMoreTxs();
// Reset and refresh when the current account changes.
txManager.L2TransactionTracker.reset();
await txManager.L2TransactionTracker.refresh();
3. Decrypt and calculate amounts in L2 transactions.
import { getL2TxAmount, getL2LPTxAmount } from "@zecrey/zecrey-mobile-core-l2";
let l2Assets = store.l2AssetsManager.getAssets(); // Data of all the L2 assets.
let decrypt = store.decryptManager.decrypt; // Method of decrypting L2 numbers.
let accountName = "bob.zecrey"; // The Zecrey account name of the current account, which is the sender of the transactions.
// 1. Amount in L2 Transfer, Withdraw, Deposit, Lock and Unlock.
let { txType, txAccounts, txFee, txAssetAId, txAssetBId, txFeeAssetId } = tx;
let amount = await getL2TxAmount(
txType,
txAccounts,
txFee,
txAssetAId,
txFeeAssetId,
decrypt,
l2Assets,
accountName
); // 12.5489
// 2. Amounts in L2 Swap, Add Liquidity and Remove Liquidity.
let amounts = await getL2LPTxAmount(
txType,
txAccounts,
txFee,
txFeeAssetId,
txAssetAId,
txAssetBId,
accountName,
l2Assets,
decrypt
); // [0.001, 0.0101]
4. Get information of transactions to be approved.
A unapproved transaction is the transaction that requires to be confirmed or rejected. If there's any unapproved transaction, no matter the app opens or not, the user should be noticed.
let unapproved = txManager.getUnapprovedTxList();
5. Deal with transactions.
No matter where the transaction request comes from, only confirmed ones get published in the end. When the user confirms a transaction, it's signed with the private key of the Zecrey account and then sent to the backend.
// 1. Create an internal transaction request.
let origin = "zecrey"; // internal origin
let { id } = await txManager.addUnapprovedL2Tx(txParams, origin);
// 3. Confirm it.
let proof = await txManager.signL2Tx(txId, decryptedPrivateKey);
let hash = await txManager.publish(txId, proof);
// 4. Or reject it
txManager.rejectL2Tx(id);
6. Params to create transaction
- Transfer
import { L2_TRANSACTION_TYPE } from "@zecrey/zecrey-mobile-core-l2";
// 1. It has to contain 1~2 payees.
// 2. Transfer amount could be 0.
// 3. Payee's name doesn't contains the '.zecrey' suffix.
// 4. The 2 payees cannot be the same.
// 5. Every payee's Zecrey account has to be active.
// 6. Sender must have enough balance to transfer and pay for the gas.
// 7. Sender's balance has to match the data in backend.
// 8. Sender can't be payee.
let params = {
action: L2_TRANSACTION_TYPE.TRANSFER, // 4
from: "bob.zecrey", // sender account name
args: {
assetId: 0,
assetDecimal: 4,
payees: [{ address: "alice", amount: "0.0001" }], // send 0.0001 to alice.zecrey
memo: "",
balance: 24.0718, // sender's balance of the asset to transfer
},
};
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
- Unlock
import { L2_TRANSACTION_TYPE } from "@zecrey/zecrey-mobile-core-l2";
// 1. Sender's balance of the gas fee asset has to match the data in backend.
// 2. It will unlock all the token of the target asset locked on the selected chain.
// 3. The balances used in params have to match the data in the Backend.
let params = {
action: L2_TRANSACTION_TYPE.UNLOCK, // 3
from: "bob.zecrey", // sender account name
args: {
// unlock all the ETH locked from Etheruem, and pay the gas fee with REY
assetId: 1,
chainId: 0, // ID of the chain that the asset locked from
gasFeeAssetId: 0,
gasFeeAssetDecimal: 4,
gasFeeAssetBalance: 1.4501,
},
};
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
- Swap
The ratio to swap token changes by the balances in the liquidity pool. Please make sure the swap amounts are not out of date.
import {
getSwapAmount,
L2_TRANSACTION_TYPE,
} from "@zecrey/zecrey-mobile-core-l2";
// 1. The account must have enough balance to pay for the swap and gas fee.
// 2. The gas asset could be the same with the swap-from asset or the swap-to asset.
// 3. Gas asset could be any L2 asset.
// 4. The balances used in params have to match the data in the Backend.
// 5. Slippage is a percentage number, in which 0.5 means 0.5%.
let assetREY = store.l2Assets.find((i) => i.assetId === 0); // asset that swap in
let assetETH = store.l2Assets.find((i) => i.assetId === 1); // asset that swap out
// Calculate swap amounts
// Get 'out' amount by the 'in' amount
let amountIn = 0.01;
let swapToAmount = await getSwapAmount(
pairIndex,
assetREY.assetId,
assetREY.decimal,
amountIn,
true,
url // optional
); // 3, without decimal places
// OR
// Get 'in' amount requires by the 'out' amount
let amountOut = 0.0003;
let swapToAmount = await getSwapAmount(
pairIndex,
assetREY.assetId,
assetREY.decimal,
amountOut,
false,
url // optional
); // 100, without decimal places
// Please remember to correct the numbers calculated with their decimal places.
let params = {
action: L2_TRANSACTION_TYPE.SWAP, // 5
from: "bob.zecrey", // sender account name
args: {
// swap with 0.01 REY for 0.0003 ETH, and pay the gas fee with REY
pairIndex: 0,
swapFromAssetId: assetREY.assetId,
swapFromAssetDecimal: assetREY.decimal,
swapFromAssetBalance: assetREY.balance,
swapFromAmount: 0.01,
swapToAssetId: assetETH.assetId,
swapToAssetDecimal: assetETH.decimal,
swapToAmount: 0.0003,
gasFeeAssetId: assetREY.assetId,
gasFeeAssetDecimal: assetREY.decimal,
gasFeeAssetBalance: assetREY.balance,
slippage: 0.5, // percentage, means 0.5%
},
};
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
- Add liquidity
import { L2_TRANSACTION_TYPE } from "@zecrey/zecrey-mobile-core-l2";
// 1. The account must have enough balance to pay for the assets and gas fee
// 2. The assets' ratio has to match the ratio in pool.
// 3. The pool ratio changes by every swap transaction.
// 4. Asset amounts are strings.
// 5. Neither amount could be 0.
// 6. REY-ETH and ETH-REY are the same.
// 7. The balances used in params have to match the data in the Backend.
// 8. Gas asset could be any L2 asset.
let assetREY = store.l2Assets.find((i) => i.assetId === 0);
let assetETH = store.l2Assets.find((i) => i.assetId === 1);
let params = {
action: L2_TRANSACTION_TYPE.ADD_LIQUIDITY, // 6
from: "bob.zecrey", // sender account name
args: {
// add liquidity with 0.01 REY and 0.0004 ETH, and pay the gas fee with REY
pairIndex: 0,
asset1Id: assetREY.assetId,
asset1Decimal: assetREY.decimal,
asset1Balance: assetREY.balance,
asset1Amount: 0.01,
asset2Id: assetETH.assetId,
asset2Decimal: assetETH.decimal,
asset2Balance: assetETH.balance,
asset2Amount: 0.0004,
gasFeeAssetId: assetREY.assetId,
gasFeeAssetDecimal: assetREY.decimal,
gasFeeAssetBalance: assetREY.balance,
},
};
// Note: the amounts added have to match the current ratio of the liquidity token pair
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
- Remove liquidity
import { L2_TRANSACTION_TYPE } from "@zecrey/zecrey-mobile-core-l2";
// 1. The account must have enough balance to burn the LP token, and pay for the gas fee.
// 2. Amount to remove is a string, and it cannot be zero.
// 3. Slippage is a percentage number, in which 0.5 means 0.5%.
// 4. REY-ETH and ETH-REY are the same.
// 5. The balances used in params have to match the data in the Backend.
// 6. Gas asset could be any L2 asset.
let assetREY = store.l2Assets.find((i) => i.assetId === 0);
let assetETH = store.l2Assets.find((i) => i.assetId === 1);
let params = {
action: L2_TRANSACTION_TYPE.REMOVE_LIQUIDITY, // 7
from: "bob.zecrey", // sender account name
args: {
// remove 0.0007 LP token, whose token pair contains REY and ETH, and pay the gas fee with REY
pairIndex: 0,
lpDecimal: 4,
lpBalance: 0.349, // sender's balance of the lp token
removeAmount: 0.0007,
slippage: 0.5, // percentage, means 0.5%
assetAId: assetREY.assetId,
assetADecimal: assetREY.decimal,
assetABalance: assetREY.balance,
assetBId: assetETH.assetId,
assetBDecimal: assetETH.decimal,
assetBBalance: assetETH.balance,
gasFeeAssetId: assetREY.assetId,
gasFeeAssetDecimal: assetREY.decimal,
gasFeeAssetBalance: assetREY.balance,
},
};
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
- Withdraw
import { L2_TRANSACTION_TYPE } from "@zecrey/zecrey-mobile-core-l2";
// 1. Withdraw amount has to be less than the user's asset balance, and it cannot be zero.
// 2. Withdraw amount has to be less than the total asset amount in the given chain.
// 3. The balances used in params have to match the data in the Backend.
let assetREY = store.l2Assets.find((i) => i.assetId === 0);
let assetETH = store.l2Assets.find((i) => i.assetId === 1);
let params = {
action: L2_TRANSACTION_TYPE.WITHDRAW, // 8
from: "bob.zecrey", // sender account name
args: {
// withdraw 0.12 ETH to the address "0x09E45d6FcF322c4D93E6aFE7076601FF10BA942E" on Ethereum, and pay the gas fee with REY
targetAddress: "0x09E45d6FcF322c4D93E6aFE7076601FF10BA942E", // L1 address, which will receive the token withdrawn
chainId: 0, // the chain, to which the token withdrawn
assetId: assetETH.assetId,
assetDecimal: assetETH.decimal,
assetBalance: assetETH.balance,
gasFeeAssetId: assetREY.assetId,
gasFeeAssetDecimal: assetREY.decimal,
gasFeeAssetBalance: assetREY.balance,
amount: 0.12,
},
};
let { id } = await txManager.addUnapprovedL2Tx({ ...params }, origin);
Calculate gas fee charged in L2 transaction
import { getGasFee, getWithdrawGasFee } from "@zecrey/zecrey-mobile-core-l2";
// Get the gas fee amount for L2 transfer, swap, and unlock assets, as well as the transactions of managing liquidity.
let fee = await getGasFee(gasFeeAssetId, url); // 0.0001, contains decimal places
// Get the gas fee amount required for L2 withdraw assets.
let withdrawAmount = 10000; // If asest decimal places is 4, it means to remove 1.0000 token.
let fee = await getWithdrawGasFee(
gasFeeAssetId,
withdrawAssetId,
withdrawAmount, // Note: decimal places removed.
url // optional
); // 3.7953, contains decimal places
Locked asset information
import {
getLockedAssetInfo,
getLockedAprByChainId,
getLockedAmountByAssetId,
} from "@zecrey/zecrey-mobile-core-l2";
// Get status of all the locked assets of each chain.
let info = await getLockedAssetInfo(url);
let aprs = info.map((i) => i.apr); // unit: 1/10000
// Get locking apr of assets on the given chain
let data = await getLockedAprByChainId(chainId, url);
// Get the total locked amount of the given asset on every chain
let data = await getLockedAmountByAssetId(assetId, url);
Liquidity token pair information
import {
getPairList,
getLpValue,
getAssetsInLP,
getMatchedLPAssets,
getPairByAssetIds,
} from "@zecrey/zecrey-mobile-core-l2";
// Get all the token pairs supported.
let LPs = await getPairList(url);
// Calculate the assets amount to receive if the given amount of lp token is removed.
let data = await getLpValue(pairIndex, removeAmount, lpDecimal, url);
// Get ratio of the liquidity token pair.
let { asset1PerAsset2, asset2PerAsset1 } = await getPairRatio(
pairIndex,
asset1Id,
url
);
let controller = new L2AssetController(...args);
let assets = controller.getAssets(); // information of all the L2 assets
// Get all the L2 assets can be found in a liquidity token pair.
let assetsInPair = getAssetsInLP(LPs, assets);
// Get all the L2 assets that a liquidity made up by it and the given asset can be found.
let assetsMatched = getMatchedLPAssets(givenAssetId, LPs, assets);
// Get Liquidity pair by asset IDs.
let LP = await getPairByAssetIds(assetAId, assetBId, LPs, url);
Withdraw limit
The liquidity is provided by locking assets that allows users to withdraw asset to L1.
import { getWithdrawLimit } from "@zecrey/zecrey-mobile-core-l2";
let limit = await getWithdrawLimit(assetId, chainId, url); // 95409, without decimal places
// Please correct the number with the asset decimal.
Chains to withdraw
import { getWithdrawChainInfo } from "@zecrey/zecrey-mobile-core-l2";
// Get all the supported L1 chains, to which assets can be withdrawn.
let info = await getWithdrawChainInfo(url);
let chains = info.find((i) => i.asset_id === assetId);
// Get all the chain Ids that the given asset can be withdrawn.
let chainIds = chains?.chains_info?.map((i) => i.chain_id) || [];
Constant
// 1. Chain ID on L2
import {
CHAIN_ID_USED_IN_L2,
MAINNET_CHAIN_ID,
} from "@zecrey/zecrey-mobile-core-l2";
// Get L2 chainId of Ethereum
let chainIdOnL2 = CHAIN_ID_USED_IN_L2[BLOCKCHAIN.ETHEREUM]; // use chain name on L1
// OR
let chainIdOnL1 = MAINNET_CHAIN_ID;
let chainIdOnL2 = CHAIN_ID_USED_IN_L2[chainIdOnL1]; // use chain ID on L1
// 2. Chain info on L1
import { getOriginalChainInfoByChainIdOnL2 } from "@zecrey/zecrey-mobile-core-l2";
// Get id and name of Ethereum on L1
let { chainId, chainName } = getOriginalChainInfoByChainIdOnL2(0, "testnet"); // {chainId: '0x4', chainName: 'Ethereum'}
// 3. L2 transaction types
import {
L2_TRANSACTION_TYPE,
L2_TRANSACTION_TYPE_STRING,
L2_TRANSACTION_TYPE_MAP,
} from "@zecrey/zecrey-mobile-core-l2";
API
POST /api/v1/crypto/getEncCollisionBatches
Request Params
| Name | Type | Size | Comment | | ---------------- | -------- | ---- | ------------------------- | | enc_data_batches | []string | | raw encryption data array |
Response Struct
{
"status": int, // status for the request
"msg": string, // response message
"err":{ //err struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": [{ //result struct
"enc_data": string
"colision_result": int // result
}]
}
GET /api/v1/info/getLayer2BasicInfo
Request Params
null
Response Struct
{
"status": int, // status for the request 0 succeed 1 fail
"msg": string, // response message
"err": { //err struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": { // result struct
}
}
POST /api/v1/tx/sendTx
Request Params
| Name | Type | Comment | | ------- | ------ | ------------------------------------------------- | | tx_type | int | tx type | | tx_info | string | JSON string including tx_type, tx_data(raw_data), |
Response Struct
{
"status": int, // status for the request
"msg": string, // response message
"err": { // struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": {
"tx_id": string, // tx id string
}
}
result struct
| Name | Type | Size | Comment | | ------------------------ | ------------ | ----- | ------------------------ | | block_committed | int | int64 | committed blocks count | | block_verified | int | int64 | verified blocks count | | total_transactions_count | int | int64 | total transactions count | | contract_addresses | string array | | string array |
GET /api/v1/tx/getTxsListByAccountIndex
Request Params
| Name | Type | Size | Comment | | ------------- | ---- | ------ | ------------- | | account_index | int | uint32 | account index | | offset | int | uint32 | page index | | limit | int | uint32 | page size |
Response Struct
{
"status": int, // status for the request
"msg": string, // response message
"err":{ // err struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": {
"limit": int,
"offset": int,
"total": int, // total size
"txs": [{}], // txs
}
}
txs struct
| Name | Type | Size | Comment | | ---------------- | -------- | -------------------------------------------- | ----------------------------------- | | tx_hash | string | 32 | tx hash | | tx_type | int | uint(Range: 1 - 64) | tx type | | gas_fee | int | int64 | transaction fee | | gas_fee_asset_id | int | uint | tx fee asset id | | tx_status | int | | Tx status | | block_height | int | | block height | | block_status | int | | block status of corresponding block | | block_id | int | | block id of corresponding block | | asset_a_id | int | uint32 | asset a id | | asset_b_id | int | uint32 | asset b id | | tx_amount | int | only counts when tx_type is withdraw/deposit | tx amount | | tx_participants | []string | Example: {"a.zecrey","b.zecrey", "c.zecrey"} | tx participants | | native_address | string | only counts when tx_type is withdraw_type | receiver address | | chain_id | int | uint32 | chain id | | created_at | int64 | timestamp | transaction create time | | memo | string | | transaction memo |
GET /api/v1/tx/getTxsListByAccountIndexAndTxType
Request Params
| Name | Type | Size | Comment | | ------------- | ---- | ------ | ------------- | | account_index | int | uint32 | account index | | tx_type | int | uint8 | tx type | | offset | int | uint32 | page index | | limit | int | uint32 | page size |
tx_type option
| Number | Comment | | ------ | -------------- | | 1 | L2Transfer | | 2 | Liquidity | | 3 | L2Swap | | 4 | WithdrawAssets | | 5 | EncryptAssets |
Response Struct
{
"status": int, // status for the request
"msg": string, // response message
"err":{ // err struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": {
"limit": int,
"offset": int,
"total": int, // total size
"txs": [{}], // txs
}
}
txs struct
| Name | Type | Size | Comment | | ---------------- | -------- | -------------------------------------------- | ----------------------------------- | | tx_hash | string | 32 | tx hash | | tx_type | int | uint(Range: 1 - 64) | tx type | | gas_fee | int | int64 | transaction fee | | gas_fee_asset_id | int | uint | tx fee asset id | | tx_status | int | | Tx status | | block_height | int | | block height | | block_status | int | | block status of corresponding block | | block_id | int | | block id of corresponding block | | asset_a_id | int | uint32 | asset a id | | asset_b_id | int | uint32 | asset b id | | tx_amount | int | only counts when tx_type is withdraw/deposit | tx amount | | tx_participants | []string | Example: {"a.zecrey","b.zecrey", "c.zecrey"} | tx participants | | native_address | string | only counts when tx_type is withdraw_type | receiver address | | chain_id | int | uint32 | chain id | | created_at | int64 | timestamp | transaction create time | | memo | string | | transaction memo |
GET /api/v1/tx/getTxByHash
Request Params
| Name | Type | Comment | | ------- | ------ | ---------------- | | tx_hash | string | transaction hash |
Response Struct
{
"status": int, // status for the request
"msg": string, // response message
"err": { // struct
"err_type": int, // err type
"err_msg": string, // error msg
},
"result": { //struct
"tx_hash": string, // tx hash
"tx_type":int, // tx type
"tx_asset_a_id": int, // asset a id
"tx_asset_b_id": int, // asset b id
"tx_details": [{ // []struct
"asset_id": int,
"asset_type": int,
"account_index": int, // account index
"account_name": string, // account name
"account_balance": string, // account balance enc before this tx
"account_delta": string, // delta amount encryption info
}],
"tx_amount": int, // tx amount
"native_address": string, // receiver address
"chain_id": int, //chain id
"tx_status": int, // tx status
"gas_fee_asset_id": int, // fee asset id
"gas_fee": int, // transaction fee
"block_height": int, // layer-2 block height
"block_status": int, // block status
"created_at": int64, // create time
"block_id": int, // block id
"memo": string, // memo
}
}
Generate proof
proveWithdraw
let proof = await ZecreyLibModules.proveWithdraw(JSON.stringify(segment));
only one input: JSON format string
type WithdrawSegmentFormat struct {
// account index
AccountIndex int `json:"account_index"`
// encryption of the balance
C string `json:"c"`
// public key
Pk string `json:"pk"`
// balance
B int64 `json:"b"`
// withdraw amount
BStar int64 `json:"b_star"`
// private key
Sk string `json:"sk"`
// asset id
AssetId int `json:"asset_id"`
// chain id
ChainId int `json:"chain_id"`
// receive address
ReceiveAddr string `json:"receive_addr"`
// fee part
// encryption of balance of the gas fee asset
C_fee string `json:"c_fee"`
// balance of gas fee asset
B_fee int64 `json:"b_fee"`
// gas fee asset id
GasFeeAssetId int `json:"gas_fee_asset_id"`
// gas fee
GasFee int64 `json:"gas_fee"`
}
proveUnlock
let proof = await ZecreyLibModules.proveUnlock(JSON.stringify(segment));
only one input: JSON format string
type UnlockSegmentFormat struct {
// chain id
ChainId int `json:"chain_id"`
// account index
AccountIndex int `json:"account_index"`
// asset id
AssetId int `json:"asset_id"`
// balance
Balance int64 `json:"balance"`
// unlock amount
DeltaAmount int64 `json:"delta_amount"`
// private key
Sk string `json:"sk"`
// fee part
// encryption of the balance of the gas fee
C_fee string `json:"c_fee"`
// gas fee balance
B_fee int64 `json:"b_fee"`
// gas fee asset id
GasFeeAssetId int `json:"gas_fee_asset_id"`
// gas fee
GasFee int64 `json:"gas_fee"`
}
proveTransfer
| Name | Type | Comment | | ------- | ------ | ------------------- | | assetId | int | unique asset id | | gasFee | int | transaction gas fee | | memo | string | memo |
let proof = await ZecreyLibModules.proveTransfer(
assetId,
gasFee,
memo,
JSON.stringify([senderSegment, payee1Segment, payee2Segment])
);
JSON format string
// TransferSegmentFormat Format is used to accept JSON string
type TransferSenderSegmentFormat struct {
// account index
AccountIndex int `json:"account_index"`
// ElGamalEnc
BalanceEnc string `json:"balance_enc"`
// Balance
Balance int64 `json:"Balance"`
// public key
Pk string `json:"pk"`
// bDelta
BDelta int64 `json:"b_delta"`
// secret key
Sk string `json:"Sk"`
}
type TransferPayeeSegmentFormat struct {
// account index
AccountIndex int `json:"account_index"`
// ElGamalEnc
BalanceEnc string `json:"balance_enc"`
// public key
Pk string `json:"pk"`
// bDelta
BDelta int64 `json:"b_delta"`
}
proveSwap
let proof = await ZecreyLibModules.proveSwap(JSON.stringify(segment));
only one input: JSON format string
/*
SwapSegmentFormat: format version of SwapSegment
*/
type SwapSegmentFormat struct {
// pair index
PairIndex int `json:"pair_index"`
// account index
AccountIndex int `json:"account_index"`
// encryption of the balance of asset A
C_uA string `json:"c_u_a"`
// user public key
Pk_u string `json:"pk_u"`
// system treasury account public key
Pk_treasury string `json:"pk_treasury"`
// asset a id
AssetAId int `json:"asset_a_id"`
// asset b id
AssetBId int `json:"asset_b_id"`
// swap amount for asset a
B_A_Delta int64 `json:"b_a_delta"`
// balance for asset a
B_u_A int64 `json:"b_u_a"`
// equal to B * (1 - slippage), B gets from the layer-2
MinB_B_Delta int64 `json:"min_b_b_delta"`
// fee rate, gets from layer-2
FeeRate int `json:"fee_rate"`
// treasury rate gets from layer-2
TreasuryRate int `json:"treasury_rate"`
// private key
Sk_u string `json:"sk_u"`
// fee part
C_fee string `json:"c_fee"`
B_fee int64 `json:"b_fee"`
GasFeeAssetId int `json:"gas_fee_asset_id"`
GasFee int64 `json:"gas_fee"`
}
proveAddLiquidity
let proof = await ZecreyLibModules.proveAddLiquidity(JSON.stringify(segment));
only one input: JSON format string
type AddLiquiditySegmentFormat struct {
PairIndex int `json:"pair_index"`
AccountIndex int `json:"account_index"`
C_uA string `json:"c_u_a"`
C_uB string `json:"c_u_b"`
Pk_pool string `json:"pk_pool"`
Pk_u string `json:"pk_u"`
AssetAId int `json:"asset_a_id"`
AssetBId int `json:"asset_b_id"`
B_uA int64 `json:"b_u_a"`
B_uB int64 `json:"b_u_b"`
B_A_Delta int64 `json:"b_a_delta"`
B_B_Delta int64 `json:"b_b_delta"`
Sk_u string `json:"sk_u"`
// fee part
C_fee string `json:"c_fee"`
B_fee int64 `json:"b_fee"`
GasFeeAssetId int `json:"gas_fee_asset_id"`
GasFee int64 `json:"gas_fee"`
}
proveRemoveLiquidity
let proof = await ZecreyLibModules.proveRemoveLiquidity(
JSON.stringify(segment)
);
type RemoveLiquiditySegmentFormat struct {
PairIndex int `json:"pair_index"`
AccountIndex int `json:"account_index"`
C_u_LP string `json:"c_u_lp"`
Pk_u string `json:"pk_u"`
B_LP int64 `json:"b_lp"`
Delta_LP int64 `json:"delta_lp"`
MinB_A_Delta int64 `json:"min_b_a_delta"`
MinB_B_Delta int64 `json:"min_b_b_delta"`
AssetAId int `json:"asset_a_id"`
AssetBId int `json:"asset_b_id"`
Sk_u string `json:"sk_u"`
// fee part
C_fee string `json:"c_fee"`
B_fee int64 `json:"b_fee"`
GasFeeAssetId int `json:"gas_fee_asset_id"`
GasFee int64 `json:"gas_fee"`
}
Error Types
| Name | Value | | -------------------------------- | -------------------------------- | | Success | success | | ErrUnmarshal | ErrUnmarshal | | ErrInvalidWithdrawParams | ErrInvalidWithdrawParams | | ErrParseEnc | ErrParseEnc | | ErrParsePoint | ErrParsePoint | | ErrParseBigInt | ErrParseBigInt | | ErrInvalidWithdrawRelationParams | ErrInvalidWithdrawRelationParams | | ErrProveWithdraw | ErrProveWithdraw | | ErrMarshalTx | ErrMarshalTx | | ErrInvalidTransferParams | ErrInvalidTransferParams | | ErrInvalidTransferRelationParams | ErrInvalidTransferRelationParams | | ErrProveTransfer | ErrProveTransfer | | ErrL2SkParams | ErrL2SkParams | | ErrInvalidEncParams | ErrInvalidEncParams | | ErrElGamalEnc | ErrElGamalEnc | | ErrInvalidDecParams | ErrInvalidDecParams | | ErrElGamalDec | ErrElGamalDec | | ErrInvalidSwapParams | ErrInvalidSwapParams | | ErrInvalidSwapRelationParams | ErrInvalidSwapRelationParams |