K2 SDK is a typescript SDk which can be used to interact with the K2 Lending protocol.
To install the SDK use the command npm i @blockswaplab/k2-sdk
One of the ways to import and initialise the SDK is:
import { K2 } from "@blockswaplab/k2-sdk";
const provider = new ethers.InfuraProvider(
"goerli",
INFURA_PROJECT_ID,
INFURA_PROJECT_SECRET
);
const signer = new ethers.Wallet(PRIV_KEY, provider);
const sdk = new K2(signer);
For using the fundSplitter
sub-class, the SDK instance can be initialised with the fund splitter contract address as follows:
const sdk = new K2(signer, fundSplitterAddress);
The SDK supports both
goerli
(until it is deprecated) andmainnet
, hence the user should choose the network as per the need.
Please note that the SDK is an
ethers.js
based SDK and hence requiresethers
based signer instance. It also returns values inethers.js
supported format. For example, it returnsBigInt
for the smart contract view functions that might returnuint
(BigNumber
in case of ethers v5).
Also note that K2 SDK v2 uses ethers v6. If you are using K2 SDK v1 which makes use of ethers v5, please create the signer and provider instances in the following way:
const provider = new ethers.providers.InfuraProvider("goerli", {
projectId: INFURA_PROJECT_ID,
projectSecret: INFURA_PROJECT_SECRET
});
const signer = new ethers.Wallet(PRIV_KEY, provider);
The SDK exposed following sub-classes:
- utils
- contracts
- k2Lending
- k2LendingDepositor
- reporterRegistry
- nodeOperatorModule
- rst
- rstModule
- k2NativeDelegationRSTIncentives
- nodeOperatorInclusionList
- partitionedLinearInterestRateModel
- pno
- fundSplitterFactory
- fundSplitter
- constants
The following readme describes all the functions and their parameters exposed by the utils
class of the K2 SDK.
This function can be used to append 0x
towards the start of a string to convert it into a hex string accepted by the contracts. If the input string already contains the 0x
, the function will return the string as is.
data: string which needs to be appended by 0x
await sdk.utils.add0x(data);
Returns hex string
This function removes 0x
from the beginning of a string. If the input string doesn't contain 0x
, it will return the string as is.
data: string to remove 0x
from
await sdk.utils.remove0x(data);
Returns string without 0x
in the beginning.
This function can be used to generate a liveness reports of the software being run.
middlewareAPI: API endpoint of the middleware
await sdk.utils.generateLivenessReport(middlewareAPI);
Returns a liveness report. Here's a sample liveness report:
{
"rpbsSelfAttestation": {
"signature": {
"z1Hat": "6404105216342bd57fa13ea8...310b519feb117f9e25087fe584f2",
"c1Hat": "1e4b7e54b1ba032ef94f2b89...b6ef01c823e20454c1166fb9aa19",
"s1Hat": "1d4a3c56bf2be321d0a6aac4...7a19ed3082b21c94357e16885278",
"c2Hat": "16755d115768ef6ebb0c45d...f4b9ffe0126b599d5d486f5574653",
"s2Hat": "1140c70f8b38105aca1d465...3bbe9f89dbc00da6646c48aa5eaa1",
"m1Hat": "6404223e9396cce38a9bf6a...48d0df6055de44898ecd0e0004ca4"
},
"commonInfo": {
"numOfValidatorsOnline": "8",
"numOfValidatorsOffline": "2",
"totalValidators": "10"
},
"publicKey": "630409260df6b583400e97...42db0603ca1fe7766d45ac42f6c0"
},
"eventType": "LIVENESS",
"version": "1",
"eventData": {
"numOfValidatorsOnline": "8",
"numOfValidatorsOffline": "2",
"totalValidators": "10",
"proposedSlashing": "0"
}
}
This function can be used to get the info from the middleware endpoint.
middlewareAPI: API endpoint of the middleware
await sdk.utils.getMiddlewareInfo(middlewareAPI);
The function returns info related to the middleware API. Here's an example of the info:
{
"VERSION":"1",
"CHAIN_ID":"5","SERVICE_PROVIDER_BORROW_ADDRESS":"0xEa0F09A471dCe34d7d3675787B1D68D841FF56D2","K2_LENDING_CONTRACT":"0x7E015fa28e05eD002Ac166D230cD3c3726CC2e7E","K2_REPORTER_REGISTRY":"0x88Cc3B6e96ef8E78b592eaDc135a0DF31991bE20",
"LIVENESS_ENDPOINT":"https://endpoint.amazonaws.com/goerli/liveness",
"REPORT_DEADLINE_LENGTH_IN_ETH_BLOCKS":"125"
}
Once the liveness or the corruption report has been generated, it needs to be verified before submitting it to the reporter registry. To verify the report, verifyReport
function should be used.
middlewareAPI: API endpoint of the middleware
report: Liveness or the corruption report returned by the respective function
await sdk.utils.verifyReport(middlewareAPI, report);
The function returns a verified report which contains the liveness report along with a signature valid for 20 minutes. Here's how a verified report looks like:
{
"inputs": {
"rpbsSelfAttestation": {
"signature": {
"z1Hat": "6404105216342bd57fa13ea8...310b519feb117f9e25087fe584f2",
"c1Hat": "1e4b7e54b1ba032ef94f2b89...b6ef01c823e20454c1166fb9aa19",
"s1Hat": "1d4a3c56bf2be321d0a6aac4...7a19ed3082b21c94357e16885278",
"c2Hat": "16755d115768ef6ebb0c45d...f4b9ffe0126b599d5d486f5574653",
"s2Hat": "1140c70f8b38105aca1d465...3bbe9f89dbc00da6646c48aa5eaa1",
"m1Hat": "6404223e9396cce38a9bf6a...48d0df6055de44898ecd0e0004ca4"
},
"commonInfo": {
"numOfValidatorsOnline": "8",
"numOfValidatorsOffline": "2",
"totalValidators": "10"
},
"publicKey": "630409260df6b583400e97...42db0603ca1fe7766d45ac42f6c0"
},
"eventType": "LIVENESS",
"version": "1",
"eventData": {
"numOfValidatorsOnline": "8",
"numOfValidatorsOffline": "2",
"totalValidators": "10",
"proposedSlashing": "100000000000000000"
}
},
"signedReport": {
"slashType": "0",
"debtor": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
"block": 9819746,
"signature": "0x3634303432336464663333323864663263623136393239373137626261356634353366323963396637623832313062343537633436633237363731383938303230386533306432346662636537316531333061366538663364346161333731616461646464653639663834346163316464616365386363663562626632653561633166643a313838333339343262373434633436323232343865323862346465353963613930633639366530623538633336393433666362643566386136383361656461653a306631316464373530393337306632316339393534643063373432313338303632323931323734393961373961386663376633353963643434353439306363353a323631363139626337656338306630613863663333643836643430373062636465313262383138303632653437396236333235623836396438323066343933633a313662383438646230666533303561363366353061346633613661383963613165326531616165626363653630363431623865633931643438323439363335343a363430343136373630313961363065396135336563323766303835363638336433653039396130616331643938376665633165636464383663636536633866643438363232306237373165643464303836343730376334666436386631386363663831333135643533303531373964346237346233363530343933346164306130326163",
"amount": {
"type": "BigInt",
"hex": "0x016345785d8a0000"
},
"identifier": 1
},
"designatedVerifierSignature": {
"deadline": 9819746,
"v": 27,
"r": "0x3a61148c3a2fdd3a9fe2c6133bbddf579333a630663f0c19dce8ecfb62484392",
"s": "0x1b4f68b48c177edf8f10f1f382cfb0c73920ecac7ed564e82909d57f119b3a11"
}
}
This function can be used to batch verify effective balance of a list of BLS public keys.
blsPublicKeys: List of BLS public keys in string format
effectiveBalances: List of effective balance in string corresponding to each BLS public key
await sdk.utils.verifyEffectiveBalance(blsPublicKeys, effectiveBalances);
The function returns a list of verified effective balance report after it has been successfully verified and error otherwise.
// Format of verified effective balance reports
[
report: {
blsKey: string,
effectiveBalance: string
},
designatedVerifierSignature: {
v: string,
r: string,
s: string
}
]
Allows to read batch values from a contract in a single RPC call.
targetContract: Address of the target contract in string format
allowFailure: Boolean. Set to true
to throw error if any one value is rejected by the contract
calldata: List of calldata in string
await sdk.utils.readUsingMulticall(targetContract, allowFailure, calldata);
Returns a list of response for each call data in the format:
{
bool success; // True if the call succeeded, false otherwise.
bytes returnData; // Return data if the call succeeded, or revert data if the call reverted.
}
The result will have to be decoded to correctly get all the values.
/// Example: decode the values from the result after using multicall read method
/// on the claimableKETHForNodeOperator function.
/// contractInterface: ABI interface of the contract that defines said function, created using ethersjs
const previewValues = multicall.map(({ success, returnData }, i) => {
if (!success) throw new Error(`Failed to resolve data for calldata[${i}]`);
return contractInterface.decodeFunctionResult(
"claimableKETHForNodeOperator",
returnData
)[0];
});
Get effective balance of a BLS public key from the consensus layer.
beaconNodeUrl: Beacon node URL string
blsPublicKey: BLS public key in string format to get effective balance of
await sdk.utils.getEffectiveBalance(beaconNodeUrl, blsPublicKey);
Effective balance in numbers
Generate corruption report from the data received from middleware API endpoint.
middlewareAPI: API endpoint of the middleware
eventData: event data of the format CorruptionEventDataT
message: string message which needs to be mentioned in the report. Default value: ''
debtorOverride: optional debtor address. Can be left null
for the function to fetch debtor address from the middlewareAPI
await sdk.utils.generateCorruptionReport(middlewareAPI, eventData, message, debtorOverride);
Returns corruption report of the format:
{
rpbsSelfAttestation: {
signature: marshalledSignature,
commonInfo: commonInfo,
publicKey: rpbsPublicKey
},
eventType: "CORRUPTION",
version: version,
eventData: eventData,
serviceProviderAddress: debtor
}
Claim effective balance for all the BLS public keys delegated by the user.
beaconNodeUrl: Beacon node URL in string
userAddress: user address in string
await sdk.utils.claimEffectiveBalance(beaconNodeUrl, userAddress);
Transaction hash
Preview claimable effective balance for all the BLS public keys delegated by the user.
userAddress: user address in string
await sdk.utils.getClaimableKETHForNodeOperator(userAddress);
List of claimable kETH in Big Numbers
Get a list of BLS public keys delegated by a node operator.
nodeRunnerAddress: Address of the node runner in string
await sdk.utils.getAllDelegetedBLSPublicKeysForNodeRunner(nodeRunner);
List of BLS public keys
List of all the delegated BLS public keys in the K2 protocol.
await sdk.utils.getAllDelegetedBLSPublicKeys();
List of BLS public keys
The SDK also exposes the contractInstance sub-class which provides an instance for contracts used in the K2 lending protocol. These instances can be used to call smart contract functions that may or may not exist in the SDK.
- k2LendingContract
- k2LendingDepositor
- ReporterRegistry
- nodeOperatorModule
- rst
- rstModule
- k2NativeDelegationRSTIncentives
- nodeOperatorInclusionList
- partitionedLinearInterestRateModel
- pnoRegistry
- lien
- fundSplitterFactory
- fundSplitter
const k2LendingContractInstance = await sdk.contracts.k2LendingContract();
const k2LendingDepositorInstance = await sdk.contracts.k2LendingDepositor();
const reporterRegistryInstance = await sdk.contracts.reporterRegistry();
const nodeOperatorModuleInstance = await sdk.contracts.nodeOperatorModule();
const rstInstance = await sdk.contracts.rst("INSERT_RST_CONTRACT_ADDRESS");
const rstModuleInstance = await sdk.contracts.rstModule();
const multicallContract = await sdk.contracts.multicallContract();
const k2NativeDelegationRSTIncentivesInstance = await sdk.contracts.k2NativeDelegationRSTIncentives();
const nodeOperatorInclusionListInstance = await sdk.contracts.nodeOperatorInclusionList();
const partitionedLinearInterestRateModelInstance = await sdk.contracts.partitionedLinearInterestRateModel();
const fundSplitterFactory = await sdk.contracts.fundSplitterFactory();
const fundSplitter = await sdk.contracts.fundSplitter(fundSplitterAddress);
const pnoRegistry = await sdk.contracts.pnoRegistry();
const lien = await sdk.contracts.lien();
All the contract instances can be directly accessed without any input parameter.
The following readme describes all the functions and their parameters exposed by the k2Lending
class of the K2 SDK. This class exposes all the important functions from the K2 Lending protocol.
This function allows anyone to get the debtor related information just by the debtor address.
debtor: ETH address of the debtor
await sdk.k2Lending.getDebtor(debtor);
Returns data of a particular debtor.
Get the borrow duration set by the contract.
await sdk.k2Lending.getBorrowDuration();
Borrow duration in BigInt.
Get the DAO address associated with the contract.
await sdk.k2Lending.getDAOAddress();
ETH address of the DAO.
Get the proposer registry ETH address.
await sdk.k2Lending.getProposerRegistry();
ETH address of the proposer registry.
Get the contract that manages the node operators eligible for native delegation.
await sdk.k2Lending.getNodeOperatorInclusionList();
ETH address of the contract that manages the node operators eligible for native delegation.
Deposits KETH into the pool and mints pool shares to the sender.
amount: amount of kETH to be deposited
await sdk.k2Lending.deposit(amount);
Transaction details if the transaction was successful.
Deposit kETH for another ETH address.
amount: amount of kETH to be deposited
recipient: ETH address to deposit kETH for
await sdk.k2Lending.depositFor(amount, recipient);
Transaction details if the transaction was successful.
Burns shares from the sender and returns the equivalent fraction of remaining KETH liquidity. Optionally, sends all KETH accrued by the lender.
amount: amount of kETH to be withdrawn
claim: true
for claiming accrued kETH
await sdk.k2Lending.withdraw(amount, claim);
Transaction details if the transaction was successful.
Claims all of the accrued KETH for the lender and sends it to the lender's address.
lender: ETH address of the lender
await sdk.k2Lending.claimKETHForLender(lender);
Transaction details if the transaction was successful.
Deposit node operator in K2 lending protocol.
blsPublicKey: BLS public key of the validator
payoutRecipient: ETH address of the recipient that would receive payout
blsSignature: BLS Signature associated with the BLS public key
ecdsaSignature: ECDSA signature
await sdk.k2Lending.nodeOperatorDeposit(blsPublicKey, payoutRecipient, blsSignature, ecdsaSignature);
Transaction details if the transaction was successful.
Withdraw node operator from the K2 Lending protocol.
recipientOverride: The recipient address
nodeOperatorAddress: ETH address of the node operator
blsPublicKey: BLS public key string
await sdk.k2Lending.nodeOperatorWithdraw(recipientOverride, nodeOperatorAddress, blsPublicKey);
Transaction details if the transaction was successful.
Kick node operator from the K2 Lending protocol.
reporterAddress: ETH address of the reporter
blsPublicKey: BLS public key
await sdk.k2Lending.nodeOperatorKick(reporterAddress, blsPublicKey);
Transaction details if the transaction was successful.
Claim ETH earned for all the BLS public keys associated with a node operator.
recipientOverride: The recipient address blsPublicKeys: List of BLS public keys to claim for
await sdk.k2Lending.nodeOperatorClaim(recipientOverride, blsPublicKeys);
Transaction details if the transaction was successful.
Slash KETH from the pool. This function can only be called by a reporter.
slashType: the slash type (liveness & corruption) debtor: the debtor address amount: the slash amount recipient: the recipient address
await sdk.k2Lending.slash(slashType, debtor, amount, recipient);
Transaction details if the transaction was successful.
Terminate debt position
debtor: ETH address of the debtor
await sdk.k2Lending.terminate(debtor);
Transaction details if the transaction was successful.
Liquidate debt position.
debtor: ETH address of the debtor
await sdk.k2Lending.liquidate(debtor);
Transaction details if the transaction was successful.
Top up kETH if it gets slashed.
debtor: address of debtor in string format
amount: amount of kETH to topup
await sdk.k2Lending.topUpSlashAmount(debtor, amount);
Transaction details if the transaction was successful.
Borrows KETH from the pool and records the debt to the debtor's address
debtPositionType: debt position type
designatedVerifier: The designated verifier of debtor
amount: The debt principal to borrow
maxSlashableAmountPerLiveness: Maximum slashable amount per liveness
maxSlashableAmountPerCorruption: Maximum slashable amount per corruption
rstConfigParams: RST config params of type RSTConfigParamsT
await sdk.k2Lending.borrow(debtPositionType, designatedVerifier, amount, maxSlashableAmountPerLiveness, maxSlashableAmountPerCorruption, rstConfigParams);
Transaction details if the transaction was successful.
Increase the SBP coverage and borrow a larger amount from K2 protocol which will cancel the old SBP.
debtPositionType: debt position type
designatedVerifier: The designated verifier of debtor
amount: The debt principal to borrow
maxSlashableAmountPerLiveness: Maximum slashable amount per liveness
maxSlashableAmountPerCorruption: Maximum slashable amount per corruption
resetDuration: If true, resets the duration else keeps the remaining duration of the borrow
await sdk.k2ending.increaseDebt(debtPositionType, designatedVerifier, amount, maxSlashableAmountPerLiveness, maxSlashableAmountPerCorruption, resetDuration);
Transaction details if the transaction was successful.
Returns the ERC-20 token supply for K2 LP.
await sdk.k2Lending.totalSupply();
Returns the total supply of the token.
The total amount that SBP can borrow from the K2 protocol.
await sdk.k2Lending.getTotalBorrowableAmount();
Returns the total amount that SBP can borrow from the protocol.
Get the outstanding interest that is left for the SBP to pay the lenders.
debtor: ETH address of the debtor
await sdk.k2Lending.getOutstandingInterest(debtor);
Returns the total outstanding interest that is left for the SBP to pay the lenders.
External hook contract. Set to address(0) to disable the hook
hookAddress: ETH address of the hook contract. Set to address(0) by default
await sdk.k2Lending.setHookAsDebtorForSBP(hookAddress);
Transaction details if the transaction was successful.
Preview claimable kETH for a BLS public key delegated by the node operator.
blsPublicKey: BLS public key in string
await sdk.k2Lending.claimableKETHForNativelyDelegatedBLSKey(blsPublicKey);
Transaction details if the transaction was successful.
The following readme describes all the functions and their parameters exposed by the k2LendingDepositor
class of the K2 SDK. This sub-class contains all the important functions from the K2 Lending depositor contract of the K2 Lending protocol.
This function can be used to get the kETH vault address registered with the contract.
await sdk.k2LendingDepositor.getKethVaultAddress();
ETH address of the kETH vault.
This function can be used to deposit tokens to the contract.
tokenAddress: Token address to deposit into the contract
amount: Amount of tokens to be deposited
await sdk.k2LendingDepositor.deposit(tokenAddress, amount);
Transaction hash if the deposit was successful.
The following readme describes all the functions and their parameters exposed by the reporterRegistry
class of the K2 SDK. This sub-class of the SDK exposes all the functions from the reporter registry contract of the K2 Lending protocol.
This function can be used to get the contract address of the K2 Lending pool.
await sdk.reporterRegistry.getk2LendingPool();
Returns contract address.
Check the contracts if the reporter is active.
reporter: ETH Address of the reporter
await sdk.reporterRegistry.isReporterActive(reporter);
Boolean, true
if active, false
otherwise.
Check the contracts if the reporter has rage quitted or not.
reporter: ETH address of the reporter
await sdk.reporterRegistry.isReporterRagequitted(reporter);
Boolean, true
if rage quitted, false
otherwise.
Check if the reporter has been already used or not.
reporter: ETH address of the reporter
await sdk.reporterRegistry.isReportUsed(reporter);
Boolean, true
if already used, false
otherwise.
Register a reporter to the reporter registry contract. The msg.sender
will be registered as the reporter.
await sdk.reporterRegistry.registerReporter();
Transaction details if the transaction is successful.
Check if the reporter is operational and can perform reports. An operational reporter is the one that is active and hasn't rage quitted.
reporter: ETH address of the reporter
await sdk.reporterRegistry.isReporterOperational(reporter);
Boolean, true
if reporter is operational, false
otherwise.
Function to submit multiple verified reports in a single transaction.
reports: List of verified reports of the following structure:
{
slashType: SlashType;
debtor: string; // Borrower address
amount: number; // Amount being slashed
identifier: number; // Unique ID to avoid double reporting
block: number; // Block number
signature: string; // Blind signature being reported
};
reportSignatures: List of signatures (designatedVerifierSignature obtained after verifying the reports) of the respective reports. Each signature follows the following structure:
{
v: number; // version
r: string; // x coordinate of the curve
s: string; // y coordinate of the curve
}
await sdk.reporterRegistry.batchSubmitReports(reports, reportSignatures);
Transaction details if the transaction is successful.
Calculate typed hash of report struct.
report: verified report of the following structure:
{
slashType: SlashType;
debtor: string; // Borrower address
amount: number; // Amount being slashed
identifier: number; // Unique ID to avoid double reporting
block: number; // Block number
signature: string; // Blind signature being reported
};
await sdk.reporterRegistry.reportTypedHash(report);
bytes32
hash string
Used to prevent double-reporting but scoped at a debtor level.
debtorAddress: Address of the debtor in string
reportIdentifier: identifier field (in string) from the report
await sdk.reporterRegistry.isDebtorReportUsed(debtorAddress, reportIdentifier);
Returns true
if report is already used, false
otherwise.
Check if report is valid or not.
report: Verified report obtained from the verifyReport
function, of the following structure:
{
slashType: SlashType;
debtor: string; // Borrower address
amount: number; // Amount being slashed
identifier: number; // Unique ID to avoid double reporting
block: number; // Block number
signature: string; // Blind signature being reported
};
reportSignature: Signature (designatedVerifierSignature obtained after verifying the reports) of the respective report. The signature follows the following structure:
{
v: number; // version
r: string; // x coordinate of the curve
s: string; // y coordinate of the curve
}
await sdk.reporterRegistry.isValidReport(report, reportSignature);
Returns true
if valid, false
otherwise.
The following readme describes all the functions and their parameters exposed by the nodeOperatorModule
class of the K2 SDK. This sub-class contains all the important functions from the K2 Node Operator Module contract of the K2 Lending protocol.
This function can be used to get the k2 Lending contract address set in the K2 Node operator module contract.
await sdk.nodeOperatorModule.getk2LendingContract();
ETH address of the k2Lending contract.
This function can be used to get the reporter registry contract address set in the K2 Node operator module contract.
await sdk.nodeOperatorModule.getReporterRegistryContract();
ETH address of the Reporter registry contract.
Report multiple BLS keys for kicking from K2 pool.
blsPublicKeys: List of BLS public keys to kick
effectiveBalances: List of effective balance in string for respective BLS public keys
designatedVerifierSignatures: List of verifier signatures of the format SignatureECDSAT (defined in the K2-SDK) for the respective BLS public keys
await sdk.nodeOperatorModule.batchNodeOperatorKick(blsPublicKeys, effectiveBalances, designatedVerifierSignatures);
Transaction details if the transaction is successful.
Batch node operator claims must come with an effective balance report.
blsPublicKeys: List of BLS public keys to kick
effectiveBalances: List of effective balance in string for respective BLS public keys
designatedVerifierSignatures: List of verifier signatures of the format SignatureECDSAT (defined in the K2-SDK) for the respective BLS public keys
await sdk.nodeOperatorModule.nodeOperatorClaim(blsPublicKeys, effectiveBalances, designatedVerifierSignatures);
Transaction details if the transaction is successful.
Check whether a kick due to effective balance is valid
blsPublicKey: BLS public key to kick
effectiveBalance: Effective balance in string for the respective BLS public key
designatedVerifierSignature: Verifier signature of the format SignatureECDSAT (defined in the K2-SDK) for the respective BLS public key
await sdk.nodeOperatorModule.isValidEffectiveBalanceReport(blsPublicKey, effectiveBalance, designatedVerifierSignature);
true
if report is valid, false
otherwise.
Check whether a BLS public key si permitted or not.
blsPublicKey: BLS public key
await sdk.nodeOperatorModule.isNewBLSKeyPermitted(blsPublicKey);
true
if BLS public key is valid, false
otherwise.
The following readme describes all the necessary functions and their parameters exposed by the rst
class of the K2 SDK.
Get address of the RST module factory that deployed the RST.
rstAddress: Address of RST contract in string
await sdk.rst.getDeployer(rstAddress);
Returns address of RST deployer
Reference to the unique SBP index in the K2 lending contract where activity can be checked.
rstAddress: Address of RST contract in string
await sdk.rst.getSBPIndex(rstAddress);
Returns uint256 SBP index in Big Numbers
For new SBPs created, the deployer uses this method so that the RST points to the new SBP index.
rstAddress: Address of RST contract in string
newSBPIndex: new SBP index in string
await sdk.rst.updateSBPIndex(rstAddress, newSBPIndex);
Transaction hash
Check if the RST token is active or not.
rstAddress: Address of RST contract in string
await sdk.rst.isActive(rstAddress);
Boolean. true
if active, false
otherwise.
The following readme describes all the necessary functions and their parameters exposed by the rstModule
class of the K2 SDK.
Get address of the K2 lending contract.
await sdk.rstModule.getK2LendingContract();
Returns address of K2 Lending contract
Address of the implementation contract that will be cloned (minimal proxy standard).
await sdk.rstModule.getImplementationContract();
Returns address of implementation contract
Check if a contract is RST or not.
contractAddress: Address of contract
await sdk.rstModule.isRST(contractAddress);
Returns true
if valid RST contract, false
otherwise.
Get the RST token associated with an SBP(Slashable borrow position) index.
sbpIndex: SBP index in string
await sdk.rstModule.sbpToRST(sbpIndex);
Returns RST token address.
RST address deployed by the debtor (SBP owner).
debtorAddress: Address of debtor
await sdk.rstModule.sbpOwnerToRST(debtorAddress);
Returns RST token address.
Get the label configured by the SBP owner for their SBP index.
sbpIndex: SBP index in string
await sdk.rstModule.sbpLabel(sbpIndex);
Returns SBP label in string.
Deploy RST. RST can only be deployed at the time of creating the SBP.
debtorAddress: Address of debtor in string
recipientAddress: Address of the account (in string) that will receive 90% of the tokens minted
dao: DAO address in string that will hold back 10% to ensure that it maintains incentives for native delegation
k2Incentives: Address in string
percentageContributionToIncentives: string
amount: Total supply that will be minted where the upper bound is the SBP principle in string
symbol: The RST token symbol used when deploying the ERC20 cloneable token in string
await sdk.rstModule.deployRST(debtorAddress, recipientAddress, dao, k2Incentives, percentageContributionToIncentives, amount, symbol);
Address of RST deployed.
Updated label of SBP index.
sbpIndex: SBP index in string
label: new SBP label in string
await sdk.rstModule.updateRSTLabel(sbpIndex, label);
Transaction hash.
The following readme describes all the functions and their parameters exposed by the k2NativeDelegationRSTIncentives
class of the K2 SDK. This sub-class contains all the important functions from the K2 Native Delegation RST Incentives contract of the K2 Lending protocol.
Get the length of the pool.
await sdk.k2NativeDelegationRSTIncentives.poolLength();
Returns the length of the pool.
Get pool ID by the reward token.
rewardToken: The RST reward token address.
await sdk.k2NativeDelegationRSTIncentives.poolIdByRewardToken(rewardToken);
Return the pool ID for the RST reward token.
Get the rewards from the last given block.
poolId: The pool ID for the RST token lastBlock: The last block number
await sdk.k2NativeDelegationRSTIncentives.getRewardFromLastBlock(poolId, lastBlock);
Returns the rewards received from the last given block.
Get the pending rewards of a user.
poolId: The pool ID for the RST token user: The user's ETH Address
await sdk.k2NativeDelegationRSTIncentives.pendingRewards(poolId, user);
Returns the pending rewards of the user.
Update all the pools.
await sdk.k2NativeDelegationRSTIncentives.massUpdatePools();
Transaction details if the transaction was successful.
Update pool for the given pool ID.
poolId: The pool ID for the pool to be updated.
await sdk.k2NativeDelegationRSTIncentives.updatePool(poolId);
Transaction details if the transaction was successful.
Farming deposit with native delegation.
poolId: The pool ID
await sdk.k2NativeDelegationRSTIncentives.nativeDelegationDeposit(poolId);
Transaction details if the transaction was successful.
K2 LP farming deposit function.
poolId: The pool ID to be withdrawn from amount: The withdraw amount
await sdk.k2NativeDelegationRSTIncentives.deposit(poolId, amount);
Transaction details if the transaction was successful.
Withdraw all the native delegation from a pool.
poolId: The pool ID for the pool to be updated.
await sdk.k2NativeDelegationRSTIncentives.nativeDelegationWithdraw(poolId);
Transaction details if the transaction was successful.
Withdraw the K2 LP tokens.
poolId: The pool ID to be withdrawn from amount: The withdraw amount
await sdk.k2NativeDelegationRSTIncentives.withdraw(poolId, amount);
Transaction details if the transaction was successful.
Claim the pending BSN tokens.
poolId: The pool ID to claim from
await sdk.k2NativeDelegationRSTIncentives.claim(poolId);
Transaction details if the transaction was successful.
Force withdraw K2 LP without rewards.
poolId: The pool ID to withdraw from
await sdk.k2NativeDelegationRSTIncentives.forceWithdraw(poolId);
Transaction details if the transaction was successful.
Force withdraw K2 LP without rewards for native delegation farmers.
poolId: The pool ID to withdraw from
await sdk.k2NativeDelegationRSTIncentives.forceWithdrawNativeDelegation(poolId);
Transaction details if the transaction was successful.
The following readme describes all the functions and their parameters exposed by the nodeOperatorInclusionList
class of the K2 SDK. This sub-class contains all the important functions from the K2 Node Operator Inclusion List contract of the K2 Lending protocol.
Compare the current counter with the global counter to see if the given bls key is permitted.
blsPublicKey: BLS public key of the validator
await sdk.nodeOperatorInclusionList.isNewBLSKeyPermitted(blsPublicKey);
Transaction details if the transaction was successful.
Notify the inclusion list that a key was added so it can increase its global counter.
blsPublicKey: BLS public key of the validator
await sdk.nodeOperatorInclusionList.onBLSKeyRegisteredToK2(blsPublicKey);
Transaction details if the transaction was successful.
Notify the inclusion list that a key was removed so it can decrease its global counter.
blsPublicKey: BLS public key of the validator
await sdk.nodeOperatorInclusionList.onBLSKeyUnregisteredToK2(blsPublicKey);
Transaction details if the transaction was successful.
The following readme describes all the functions and their parameters exposed by the partitionedLinearInterestRateModel
class of the K2 SDK. This sub-class contains all the important functions from the K2 Partitioned Linear Interest Rate Model contract of the K2 Lending protocol.
Get the max utilisation percentage of the pool at 100% utilisation.
assumedLiquidity: Total liquidity in the pool, including available and borrowed funds borrowedLiquidity: Liquidity borrowed from the pool borrowAmount: Borrow amount
await sdk.partitionedLinearInterestRateModel.getUtilizationRatio(assumedLiquidity, borrowedLiquidity, borrowAmount);
Returns the max utilization percentage.
Upper bound for the ETH slashing amount that can take place for a given liveness event.
assumedLiquidity: Total liquidity in the pool, including available and borrowed funds borrowedLiquidity: Liquidity borrowed from the pool borrowAmount: Borrow amount
await sdk.partitionedLinearInterestRateModel.maxSlashableAmountPerLivenessUpper(assumedLiquidity, borrowedLiquidity, borrowAmount);
Returns the max ETH slashing amount possible for a given liveness event.
Upper bound for the ETH slashing amount that can take place for a given corruption event.
assumedLiquidity: Total liquidity in the pool, including available and borrowed funds borrowedLiquidity: Liquidity borrowed from the pool borrowAmount: Borrow amount
await sdk.partitionedLinearInterestRateModel.maxSlashableAmountPerCorruptionUpper(assumedLiquidity, borrowedLiquidity, borrowAmount);
Returns the max ETH slashing amount possible for a given corruption event.
Get the current interest rate based on assumed (total) and available liquidity.
assumedLiquidity: Total liquidity in the pool, including available and borrowed funds borrowedLiquidity: Liquidity borrowed from the pool borrowAmount: Borrow amount maxSlashableAmountPerLiveness: Maximum slashable amount per liveness maxSlashableAmountPerCorruption: Maximum slashable amount per corruption
await sdk.partitionedLinearInterestRateModel.getInterestRate(assumedLiquidity, borrowedLiquidity, borrowAmount, maxSlashableAmountPerLiveness, maxSlashableAmountPerCorruption);
Returns the current interest rate in RAY format.
Get the expected max borrow amount for SBP using interest.
interestAmount: The interest amount currentBorrowAmount: Curent debt principal maxSlashableAmountPerLiveness: Maximum slashable amount per liveness maxSlashableAmountPerCorruption: Maximum slashable amount per corruption duration: Borrow duration
await sdk.partitionedLinearInterestRateModel.getMaxBorrowableAmount(interestAmount, currentBorrowAmount, maxSlashableAmountPerLiveness, maxSlashableAmountPerCorruption, duration);
Returns the expected max borrow amount using interest.
Get the expected interest accrued over a duration, assuming interest rate doesn't change after the initial borrow.
newBorrowAmount: The debt principal to compute interest for currentBorrowAmount: Curent debt principal maxSlashableAmountPerLiveness: Maximum slashable amount per liveness maxSlashableAmountPerCorruption: Maximum slashable amount per corruption duration: Borrow duration
await sdk.partitionedLinearInterestRateModel.getExpectedInterest(newBorrowAmount, currentBorrowAmount, maxSlashableAmountPerLiveness, maxSlashableAmountPerCorruption, duration);
Returns the expected interest accrued over a duration.
The following readme describes all the functions and their parameters exposed by the pno
class of the K2 SDK. This sub-class contains all the important functions from the PNO registry and Lien contracts of the K2 Lending protocol.
Handle the case where delegated recipient is being adjusted to make sure no redelegations remain when lien is in force.
currentRecipient: Address of the current recipient
await sdk.pno.onDelegatedRecipientSet(currentRecipient);
Transaction details if the transaction was successful.
Poke the PNO registry to allow it to check whether kNetwork is mapped to current SBP.
debtor: ETH address of the debtor
await sdk.pno.onSBPUpdated(debtor);
Transaction details if the transaction was successful.
SBP owner can call this function to spin up their own kNetwork which will take care of deploying a fund splitter.
defaultRewardToken: Address of the default reward token
await sdk.pno.createKNetwork(defaultRewardToken);
Transaction details if the transaction was successful.
Allows the lien contract to ban a node operator in the event that a PNO has severely violated protocol rules.
sbpIndexId: SBP index in string
pno: Address of the PNO
await sdk.pno.banNodeOperator(sbpIndexId, pno);
Transaction details if the transaction was successful.
Allows the DAO to manage the global PNO inclusion list.
pno: Address of the PNO
enabled: Boolean value, true if enabled
await sdk.pno.managePNO(pno, enabled);
Transaction details if the transaction was successful.
Allow a SBP owner to use a PNO from the global inclusion list in their kNetwork.
pno: Address of the PNO
await sdk.pno.removePNO(pno);
Transaction details if the transaction was successful.
Allow a kNetwork to enable PNO gatekeeping for their network before and after network creation.
await sdk.pno.togglePNOGatekeepingForKNetwork();
Transaction details if the transaction was successful.
Allow a kNetwork that has gatekeeping enabled to manage inclusion list for the opt in to work.
PNOs: Array of all PNO addresses enabled: Boolean value, true if enabled
await sdk.pno.manageKNetworkInclusionList(PNOs, enabled);
Transaction details if the transaction was successful.
Lets the PNO to opt into node running for a kNetwork.
sbpIndexId: SBP index in string
await sdk.pno.optIntoKNetwork(sbpIndexId);
Transaction details if the transaction was successful.
Lets the PNO to opt out of node running for a kNetwork.
sbpIndexId: SBP index in string
await sdk.pno.optOutOfKNetwork(sbpIndexId);
Transaction details if the transaction was successful.
Allow PNO to set their fee recipient across all kNetwork payout processing fund splitter contracts.
feeRecipient: Address of the fee recipient
await sdk.pno.setPNOFeeRecipient(feeRecipient);
Transaction details if the transaction was successful.
Re-delegate K2 re-staked balance to a PNO using K2 LP balance.
pno: Address of the PNO
amount: Restaked balance to be re-delegated
await sdk.pno.reDelegateToPreferredNodeOperator(pno, amount);
Transaction details if the transaction was successful.
Remove the re-delegation given to a PNO by a K2 LP balance and obtain K2 LP back.
pno: Address of the PNO
amount: Re-delegated amount to be obtained back
await sdk.pno.removeRedelegation(pno, amount);
Transaction details if the transaction was successful.
Re-delegate K2 re-staked balance to a PNO using K2 native delegation balance.
pno: Address of the PNO
amountToRedelegateInETH: Amount to be re-delegated in ETH
await sdk.pno.reDelegateToPreferredNodeOperatorFromNativeDelegation(pno, amountToRedelegateInETH);
Transaction details if the transaction was successful.
Remove re-delegation from a PNO that was given from a native delegation K2 balance.
pno: Address of the PNO
amountToRedelegateInETH: Re-delegated amount to be obtained back
await sdk.pno.removeRedelegationFromNativeDelegation(pno, amountToRedelegateInETH);
Transaction details if the transaction was successful.
Query function to get total re-delegations to PNO in ETH.
user: ETH address of the user
pno: Address of the PNO
await sdk.pno.totalReDelegationsInETHToPNO(user, pno);
Returns the total re-delegated amount in bigint.
Query function to get total re-delegations to PNO in ETH for the given timestamp.
user: ETH address of the user
pno: Address of the PNO
timestamp: The timestamp value in string
await sdk.pno.totalReDelegationsInETHToPNOForTimestamp(user, pno, timestamp);
Returns the total re-delegated amount in bigint.
To check if the PNO is eligible to receive liquid re-delegations.
pno: Address of the PNO
await sdk.pno.isPreferredNodeOperator(pno);
Returns true if the PNO is eligible, else false.
Check if re-delegations have been first removed when trying to burn K2 LP.
user: ETH address of the user amount: Withdraw amount in string
await sdk.pno.onWithdraw(user, amount);
Transaction details if the transaction was successful.
Check the active re-delegations before allowing the node operator to remove their native delegation.
user: ETH address of the user.
await sdk.pno.onNodeOperatorWithdraw(user);
Transaction details if the transaction was successful.
Allow a kNetwork to specify the public key of their PNO designated verifier for slashing.
designatedVerifier: Address of the PNO designated verifier
await sdk.pno.configureDesignatedVerifierAsKNetwork(designatedVerifier);
Transaction details if the transaction was successful.
Slash the given PNO.
kNetwork: Address of the kNetwork
reportIdentifier: Nonce for the report
pno: Address of the PNO
amount: The slash amount in string
designatedVerifierSignature: List of verifier signatures of the format SignatureECDSAT (defined in the K2-SDK) for the respective BLS public keys
deadline: Deadline for the validity of the signatures
await sdk.pno.slashPNO(kNetwork, reportIdentifier, pno, amount, designatedVerifierSignature, deadline);
Transaction details if the transaction was successful.
Poke the Lien to allow it to check whether kNetwork is mapped to current SBP.
debtor: ETH address of the debtor
await sdk.pno.onSBPUpdatedLien(debtor);
Transaction details if the transaction was successful.
Check if the given report is valid.
kNetwork: Address of the kNetwork
reportIdentifier: Nonce for the report
pno: Address of the PNO
amount: The slash amount in string
designatedVerifierSignature: List of verifier signatures of the format SignatureECDSAT (defined in the K2-SDK) for the respective BLS public keys
deadline: Deadline for the validity of the signatures
await sdk.pno.isValidReport(kNetwork, reportIdentifier, pno, amount, designatedVerifierSignature, deadline);
Return true if the report is valid, else false.
Get the typed hash of the given report.
kNetwork: Address of the kNetwork
reportIdentifier: Nonce for the report
pno: Address of the PNO
amount: The slash amount in string
deadline: Deadline for the validity of the signatures
await sdk.pno.reportTypedHash(currentRecipient);
Returns the 32-byte hash of the report.
The following readme describes all the functions and their parameters exposed by the fundSplitterFactory
class of the K2 SDK. This sub-class contains all the important functions from the Fund Splitter factory contract of the K2 Lending protocol.
SBP owner will call this function to remap the fund splitter if required.
await sdk.fundSplitterFactory.remapFundSplitterIfRequired();
Transaction hash if the deposit was successful.
SBP owner will call this function to deploy a fund splitter instance.
debtor: ETH address of the debtor
defaultRewardToken: Address of the reward token for the fund splitter instance
await sdk.fundSplitterFactory.deployFundSplitter(debtor, defaultRewardToken);
Returns the address of the deployed fund splitter instance.
The following readme describes all the functions and their parameters exposed by the fundSplitter
class of the K2 SDK. This sub-class contains all the important functions from the Fund Splitter contract of the K2 Lending protocol.
Update the SBP index.
sbpIndex: The SBP index in string
await sdk.fundSplitter.updateSBPIndex(sbpIndex);
Transaction details if the transaction was successful.
Distribute the new rewards to the PNOs and redelegators.
rewardToken: The address of the reward token
rewardAmount: The reward amount in string
PNOs: Array of ETH addresses of the PNOs
await sdk.fundSplitter.distributeNewRewards(rewardToken, rewardAmount, PNOs);
Transaction details if the transaction was successful.
Claim rewards from the redelegation bucket after it has been distributed.
user: The ETH address of the user
distributionIndex: The distribution index in string
PNOs: Array of ETH addresses of the PNOs
await sdk.fundSplitter.claimFromRedelegationBucket(user, distributionIndex, PNOs);
Transaction details if the transaction was successful.
Claim PNO earnings from the PNO bucket after it has been distributed.
pno: The ETH address of the PNO
rewardTokens: Array of reward token addresses
await sdk.fundSplitter.claimFromPNOBucket(pno, rewardTokens);
Transaction details if the transaction was successful.
Hook function to track PNOs enabled status.
pno: The ETH address of the PNO
enabled: Boolean value, true if enabled
await sdk.fundSplitter.onPNOEnabled(pno, enabled);
Transaction details if the transaction was successful.
Get the historical earnings for the given PNO, for the default reward token.
pno: The ETH address of the PNO
await sdk.fundSplitter.pnoHistoricalEarnings(pno);
Returns the historical PNO earnings in bigint.
Get the historical earnings for the given PNO and the given reward token.
pno: The ETH address of the PNO
rewardToken: Address of the reward token
await sdk.fundSplitter.pnoHistoricalEarningsForRewardToken(pno, rewardToken);
Returns the historical PNO earnings in bigint.
Checks if the PNO was enabled at the given snapshot.
pno: The ETH address of the PNO
snapshotId: The snapshot id in string
await sdk.fundSplitter.isPNOEnabledAt(pno, snapshotId);
Return true if the PNO was enabled, else false.