Skip to content

Commit

Permalink
Merge pull request #291 from interlay/dan/beta-v2-types
Browse files Browse the repository at this point in the history
feat: Upgrade types, remove paged iterator
  • Loading branch information
daniel-savu authored May 27, 2021
2 parents 46034e6 + c01b66b commit ed02b20
Show file tree
Hide file tree
Showing 15 changed files with 69 additions and 202 deletions.
16 changes: 8 additions & 8 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: "3.8"
services:
polkabtc:
image: "registry.gitlab.com/interlay/btc-parachain:0-7-2-a06ada7d-1622023912"
image: "registry.gitlab.com/interlay/btc-parachain:0-7-4-7c02930d-1622122540"
command:
- btc-parachain
- --rpc-external
Expand Down Expand Up @@ -58,7 +58,7 @@ services:
- "3002:3002"
staked-relayer:
# only start staked relayer after mining to prevent long catch-up
image: "registry.gitlab.com/interlay/polkabtc-clients/staked-relayer:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/staked-relayer:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -73,7 +73,7 @@ services:
BITCOIN_RPC_PASS: rpcpassword
RUST_LOG: info
oracle:
image: "registry.gitlab.com/interlay/polkabtc-clients/oracle:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/oracle:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -84,7 +84,7 @@ services:
environment:
RUST_LOG: info
faucet:
image: "registry.gitlab.com/interlay/polkabtc-clients/faucet:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/faucet:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -98,7 +98,7 @@ services:
ports:
- "3036:3036"
vault_1:
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -112,7 +112,7 @@ services:
environment:
<<: *client-env
vault_2:
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -126,7 +126,7 @@ services:
environment:
<<: *client-env
vault_3:
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-5"
command:
- /bin/sh
- -c
Expand All @@ -140,7 +140,7 @@ services:
environment:
<<: *client-env
vault_to_liquidate:
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-2"
image: "registry.gitlab.com/interlay/polkabtc-clients/vault:0-7-5"
command:
- /bin/sh
- -c
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@interlay/polkabtc",
"version": "0.15.5",
"version": "0.15.6",
"description": "JavaScript library to interact with PolkaBTC",
"main": "build/index.js",
"typings": "build/index.d.ts",
Expand Down Expand Up @@ -39,7 +39,7 @@
"engineStrict": true,
"dependencies": {
"@interlay/esplora-btc-api": "0.4.0",
"@interlay/polkabtc-types": "0.7.2",
"@interlay/polkabtc-types": "0.7.3",
"@polkadot/api": "4.8.1",
"@polkadot/typegen": "4.8.1",
"@types/big.js": "6.0.2",
Expand Down
2 changes: 1 addition & 1 deletion src/json/parachain.json

Large diffs are not rendered by default.

10 changes: 0 additions & 10 deletions src/parachain/issue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import Big from "big.js";
import { IssueRequest } from "../interfaces/default";
import { DefaultVaultsAPI, VaultsAPI } from "./vaults";
import {
pagedIterator,
decodeFixedPointType,
roundUpBtcToNearestSatoshi,
encodeParachainRequest,
Expand Down Expand Up @@ -85,11 +84,6 @@ export interface IssueAPI extends TransactionAPI {
* @returns An array containing the issue requests
*/
list(): Promise<IssueRequestExt[]>;
/**
* @param perPage Number of issue requests to iterate through at a time
* @returns An AsyncGenerator to be used as an iterator
*/
getPagedIterator(perPage: number): AsyncGenerator<IssueRequest[]>;
/**
* @param account The ID of the account whose issue requests are to be retrieved
* @returns A mapping from the issue request ID to the issue request object, corresponding to the requests of
Expand Down Expand Up @@ -221,10 +215,6 @@ export class DefaultIssueAPI extends DefaultTransactionAPI implements IssueAPI
return new Big(decodeFixedPointType(issueFee));
}

getPagedIterator(perPage: number): AsyncGenerator<IssueRequest[]> {
return pagedIterator<IssueRequest>(this.api.query.issue.issueRequests, perPage);
}

async getRequestById(issueId: H256): Promise<IssueRequestExt> {
const head = await this.api.rpc.chain.getFinalizedHead();
return encodeIssueRequest(await this.api.query.issue.issueRequests.at(head, issueId), this.btcNetwork);
Expand Down
12 changes: 1 addition & 11 deletions src/parachain/redeem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Big from "big.js";
import { VaultsAPI, DefaultVaultsAPI } from "./vaults";
import {
decodeBtcAddress,
pagedIterator,
decodeFixedPointType,
encodeParachainRequest,
btcToSat,
Expand Down Expand Up @@ -96,11 +95,6 @@ export interface RedeemAPI extends TransactionAPI {
* @param account Keyring account
*/
setAccount(account: AddressOrPair): void;
/**
* @param perPage Number of redeem requests to iterate through at a time
* @returns An AsyncGenerator to be used as an iterator
*/
getPagedIterator(perPage: number): AsyncGenerator<RedeemRequest[]>;
/**
* @param account The ID of the account whose redeem requests are to be retrieved
* @returns A mapping from the redeem request ID to the redeem request object, corresponding to the requests of
Expand Down Expand Up @@ -193,7 +187,7 @@ export class DefaultRedeemAPI extends DefaultTransactionAPI implements RedeemAPI

async request(amount: Big, btcAddressEnc: string, vaultId?: AccountId): Promise<RequestResult> {
if (!vaultId) {
vaultId = await this.vaultsAPI.selectRandomVaultIssue(amount);
vaultId = await this.vaultsAPI.selectRandomVaultRedeem(amount);
}
const amountSat = this.api.createType("Wrapped", btcToSat(amount.toString()));
const btcAddress = this.api.createType("BtcAddress", decodeBtcAddress(btcAddressEnc, this.btcNetwork));
Expand Down Expand Up @@ -333,10 +327,6 @@ export class DefaultRedeemAPI extends DefaultTransactionAPI implements RedeemAPI
return decodeFixedPointType(premiumRedeemFee);
}

getPagedIterator(perPage: number): AsyncGenerator<RedeemRequest[]> {
return pagedIterator<RedeemRequest>(this.api.query.redeem.redeemRequests, perPage);
}

async getRequestById(redeemId: H256): Promise<RedeemRequestExt> {
const head = await this.api.rpc.chain.getFinalizedHead();
return encodeRedeemRequest(await this.api.query.redeem.redeemRequests.at(head, redeemId), this.btcNetwork);
Expand Down
8 changes: 1 addition & 7 deletions src/parachain/staked-relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,7 @@ export class DefaultStakedRelayerAPI extends DefaultTransactionAPI implements St
async list(): Promise<AccountId[]> {
const head = await this.api.rpc.chain.getFinalizedHead();
const stakedRelayersMap = await this.api.query.wrappedRelayerRewards.stake.entriesAt(head);
return stakedRelayersMap
.filter(
(v) => (new Big(v[1].toString()) > new Big(0))
)
.map(
(v) => storageKeyToFirstInner(v[0])
);
return stakedRelayersMap.map((v) => storageKeyToFirstInner(v[0]));
}

async getMonitoredVaultsCollateralizationRate(): Promise<Map<AccountId, Big>> {
Expand Down
28 changes: 2 additions & 26 deletions src/parachain/vaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
} from "../interfaces/default";
import {
FIXEDI128_SCALING_FACTOR,
pagedIterator,
planckToDOT,
decodeFixedPointType,
encodeBtcAddress,
Expand Down Expand Up @@ -78,13 +77,6 @@ export interface VaultsAPI extends TransactionAPI {
* @returns An array containing the vaults with non-zero backing collateral
*/
list(): Promise<VaultExt[]>;
/**
* This function is not finalized
*
* @returns An array containing the vaults, paged. This function is meant to be used as an
* iterator
*/
listPaged(): Promise<VaultExt[]>;
/**
* Fetch the issue requests associated with a vault
*
Expand All @@ -107,11 +99,6 @@ export interface VaultsAPI extends TransactionAPI {
* @returns A map with replace ids to replace requests involving said vault as new vault and old vault
*/
mapReplaceRequests(vaultId: AccountId): Promise<Map<H256, ReplaceRequestExt>>;
/**
* @param perPage Number of vaults to iterate through at a time
* @returns An AsyncGenerator to be used as an iterator
*/
getPagedIterator(perPage: number): AsyncGenerator<Vault[]>;
/**
* @param vaultId The ID of the vault to fetch
* @returns A vault object
Expand Down Expand Up @@ -154,7 +141,7 @@ export interface VaultsAPI extends TransactionAPI {
* @param amount Amount to issue, denominated in BTC
* @returns The required collateral for issuing, denominated in DOT
*/
getRequiredCollateralForWrapped(amount: Big): Promise<Big>;
getRequiredCollateralForWrapped(amount: Big): Promise<Big>;
/**
* @param vaultId The vault account ID
* @returns The amount of PolkaBTC issued by the given vault
Expand Down Expand Up @@ -313,14 +300,7 @@ export class DefaultVaultsAPI extends DefaultTransactionAPI implements VaultsAPI
const head = await this.api.rpc.chain.getFinalizedHead();
const vaultsMap = await this.api.query.vaultRegistry.vaults.entriesAt(head);
return vaultsMap
.map((v) => encodeVault(v[1], this.btcNetwork))
.filter(v => new Big(v.backing_collateral.toString()) > new Big(0));
}

// TODO: Finish or remove this function
async listPaged(): Promise<VaultExt[]> {
const vaultsMap = await this.api.query.vaultRegistry.vaults.entriesPaged({ pageSize: 1 });
return vaultsMap.map((v) => encodeVault(v[1], this.btcNetwork));
.map((v) => encodeVault(v[1], this.btcNetwork));
}

async mapIssueRequests(vaultId: AccountId): Promise<Map<H256, IssueRequestExt>> {
Expand Down Expand Up @@ -365,10 +345,6 @@ export class DefaultVaultsAPI extends DefaultTransactionAPI implements VaultsAPI
}
}

getPagedIterator(perPage: number): AsyncGenerator<Vault[]> {
return pagedIterator<Vault>(this.api.query.vaultRegistry.vaults, perPage);
}

async get(vaultId: AccountId): Promise<VaultExt> {
const head = await this.api.rpc.chain.getFinalizedHead();
const vault = await this.api.query.vaultRegistry.vaults.at(head, vaultId);
Expand Down
1 change: 0 additions & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export * from "./bitcoin";
export * from "./currency";
export * from "./encoding";
export * from "./pagedIterator";
export * from "./constants";
export * from "./bitcoin-core-client";
export * from "./issue";
Expand Down
104 changes: 53 additions & 51 deletions src/utils/issue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,66 +28,68 @@ export async function issue(
triggerRefund = false,
network = "regtest",
): Promise<IssueResult> {
const treasuryAPI = new DefaultTreasuryAPI(api);
const bitcoinjsNetwork = getBitcoinNetwork(network);
const issueAPI = new DefaultIssueAPI(api, bitcoinjsNetwork, electrsAPI);
const collateralAPI = new DefaultCollateralAPI(api);
try {
const treasuryAPI = new DefaultTreasuryAPI(api);
const bitcoinjsNetwork = getBitcoinNetwork(network);
const issueAPI = new DefaultIssueAPI(api, bitcoinjsNetwork, electrsAPI);
const collateralAPI = new DefaultCollateralAPI(api);

issueAPI.setAccount(issuingAccount);
const requesterAccountId = api.createType("AccountId", issuingAccount.address);
const initialBalanceDOT = await collateralAPI.balance(requesterAccountId);
const initialBalancePolkaBTC = await treasuryAPI.balance(requesterAccountId);
const blocksToMine = 3;
const vaultAccountId = vaultAddress ? api.createType("AccountId", vaultAddress) : undefined;
issueAPI.setAccount(issuingAccount);
const requesterAccountId = api.createType("AccountId", issuingAccount.address);
const initialBalanceDOT = await collateralAPI.balance(requesterAccountId);
const initialBalancePolkaBTC = await treasuryAPI.balance(requesterAccountId);
const blocksToMine = 3;
const vaultAccountId = vaultAddress ? api.createType("AccountId", vaultAddress) : undefined;

// request issue
const requestResult = await issueAPI.request(amount, vaultAccountId);
let issueRequest;
try {
issueRequest = await issueAPI.getRequestById(requestResult.id);
} catch (e) {
// IssueCompleted errors occur when multiple vaults attempt to execute the same request
console.log(e);
}
// request issue

const requestResult = await issueAPI.request(amount, vaultAccountId);
const issueRequest = await issueAPI.getRequestById(requestResult.id);


let amountAsBtc = new Big(satToBTC(
(issueRequest as IssueRequestExt).amount.add((issueRequest as IssueRequestExt).fee).toString()
));
let amountAsBtc = new Big(satToBTC(
(issueRequest as IssueRequestExt).amount.add((issueRequest as IssueRequestExt).fee).toString()
));

if (triggerRefund) {
// Send 1 more Btc than needed
amountAsBtc = amountAsBtc.add(1);
}
if (triggerRefund) {
// Send 1 more Btc than needed
amountAsBtc = amountAsBtc.add(1);
}

// send btc tx
const vaultBtcAddress = requestResult.issueRequest.btc_address;
if (vaultBtcAddress === undefined) {
throw new Error("Undefined vault address returned from RequestIssue");
}
// send btc tx
const vaultBtcAddress = requestResult.issueRequest.btc_address;
if (vaultBtcAddress === undefined) {
throw new Error("Undefined vault address returned from RequestIssue");
}

const txData = await bitcoinCoreClient.sendBtcTxAndMine(vaultBtcAddress, amountAsBtc, blocksToMine);
const txData = await bitcoinCoreClient.sendBtcTxAndMine(vaultBtcAddress, amountAsBtc, blocksToMine);

if (autoExecute === false) {
// execute issue, assuming the selected vault has the `--no-issue-execution` flag enabled
await issueAPI.execute(requestResult.id.toString(), txData.txid);
} else {
// wait for vault to execute issue
while (!(await issueAPI.getRequestById(requestResult.id)).status.isCompleted) {
await sleep(1000);
if (autoExecute === false) {
// execute issue, assuming the selected vault has the `--no-issue-execution` flag enabled
await issueAPI.execute(requestResult.id.toString(), txData.txid);
} else {
// wait for vault to execute issue
while (!(await issueAPI.getRequestById(requestResult.id)).status.isCompleted) {
await sleep(1000);
}
}
}

const [finalBalancePolkaBTC, finalBalanceDOT] = await Promise.all([
treasuryAPI.balance(requesterAccountId),
collateralAPI.balance(requesterAccountId)
]);
return {
request: requestResult,
initialDotBalance: initialBalanceDOT,
finalDotBalance: finalBalanceDOT,
initialPolkaBtcBalance: initialBalancePolkaBTC,
finalPolkaBtcBalance: finalBalancePolkaBTC,
};
const [finalBalancePolkaBTC, finalBalanceDOT] = await Promise.all([
treasuryAPI.balance(requesterAccountId),
collateralAPI.balance(requesterAccountId)
]);
return {
request: requestResult,
initialDotBalance: initialBalanceDOT,
finalDotBalance: finalBalanceDOT,
initialPolkaBtcBalance: initialBalancePolkaBTC,
finalPolkaBtcBalance: finalBalancePolkaBTC,
};
} catch (e) {
// IssueCompleted errors occur when multiple vaults attempt to execute the same request
console.log(e);
throw new Error(`Issuing failed: ${e.message}`);
}
}

export function sleep(ms: number): Promise<void> {
Expand Down
Loading

0 comments on commit ed02b20

Please sign in to comment.