PayChainCode - frictionless RTP payment and settlement
Payment rail today is relay pattern based system .... Passing the baton from one to another
Across the planet earth, at the time of writing (future with other planets as well), most of the banks don’t have an established financial relationship, they have to search the SWIFT network for a correspondent bank that has a relationship with both banks and can settle the transaction — for a fee. Each correspondent bank maintains different ledgers, at the originating bank and the receiving bank, which means that these different ledgers have to be reconciled at the end of the day.
SWIFT messages are one-way, much like emails, which mean that transactions can’t be settled until each party has screened the transaction.
The centralized SWIFT protocol doesn’t actually send the funds, it simply sends the payment orders. The actual money is then processed through a system of intermediaries. Each intermediary adds additional cost to the transaction and creates a potential point of failure. Further, most of the B2B payments require manual intervention, each taking between 15-20 minutes.
This challenges the banking experience to their clients as Payment is not about just sending instructions.. Customers expect to be settled instantaneously while they are in the mind and soul of the business transaction..
From one way - fire and forget model into bi directional real time payment and settlements
What Are Real-Time Payments? Real-time payments or RTP are payments that happen almost instantaneously, meaning they are initiated and settled in seconds. The real-time payment rail is a digital infrastructure that enables real-time payments. The ideal real-time payment infrastructure has 24x7x365 access, meaning they are online to process payments anytime needed, including weekends and holidays.
Some of the more common use cases for real-time payments are:
RT payment infrastructure is already live in 50 + countries including Singapore, India, Poland, US, etc. But it's limited to the domestic banking network.
What are the blocking factors
Unchanging user behaviour. Often, customers entrenched in specific financial habits might not like change. Merchants and traders used to traditional payment methods might be reluctant to invest in setting up new processes.
Entering into distributed ledger model- blockchain
Platform based on the blockchain and distributed ledger (DLT) can help banks protect transaction information in several ways:
An Accenture survey among 8 global banks found that blockchain technology could bring down the average cost of clearing and settling transactions by $10B annually.
Getting even with private" or "permissioned" blockchains
Compare that open, permissionless blockchain to the "private" or "permissioned" blockchains that established tech and financial services players, along with a gaggle of startups, are developing on their own or through consortia.
Rather than a trustless network of thousands of strangers, they propose to build small networks of known, vetted actors – or in some cases, to keep the blockchain to themselves. The result makes compliance with Anti-Money Laundering and Know Your Customer laws easier but at some point, these purported blockchains have little to do with the innovation that underpins bitcoin.
Industrialization
Unlike SWIFT messages are one-way, much like emails, which mean that transactions can’t be settled until each party has screened the transaction. By integrating directly with a bank’s existing databases and ledgers, Ripple’s xCurrent product provides banks with a faster, two-way communication protocol that permits real-time messaging and settlement.
Ripple currently has over 300 customers in over 40 countries signed up to experiment with its blockchain network.
SWIFT ‘s GPI
Against the backdrop of competition with Ripple, SWIFT seeks to promote GPI – its own new global payment system. It is reported that GPI has already accepted 450 banks, and that the daily settlement of payments is $ 300 billion. Now 80% of international payments are made using GPI. At the same time, GPI accounts for 50% of payments credited within 30 minutes, and 40% of payments credited in 5 minutes.
At the same time, SWIFT notes that the GPI system is not designed to accelerate payments, but it is quite fast. The GPI system has now significantly improved such aspects of payments as cost, speed, transparency, convenience and security.
SWIFT embrace Blockchain as well
As Ripple is trying to take over global payments, SWIFT and the banks that are currently the dominant global payment providers. will be integrating the Corda technology in a test network for a proof-of-concept experiment. R3/Corda are companies that are linked to Ripple and who utilize the XRP cryptocurrency. R3 provides DLT (distributed ledger technology) and Corda utilizes that technology to settle payments in fiat or cryptocurrency, with the first crypto being used being XRP.
Projects like Ripple and R3 are working with traditional banks to bring greater efficiency to the sector. They’re looking to decentralize systems on a smaller scale than public blockchains by connecting financial institutions to the same ledger in order to increase efficiency of transactions.
Banking Enterprise scale factors
High-performance enterprises like Bank and financial institutions have very different needs from individual users on a peer-to-peer network. They need to: manage sensitive data in high volume, track quality, and hold themselves accountable to safety and regulatory standards in their industries.
Enterprise needs ultimately fall into 4 categories when it comes to blockchain technology:
Hyperledger Besu
To cater such needs, we can look at Hyperledger Besu. It is an Ethereum client designed to be enterprise-friendly for both public and private permissioned network use cases. It can also be ran on test networks such as Rinkeby, Ropsten, and Görli. Hyperledger Besu includes several consensus algorithms including PoW, and PoA (IBFT, IBFT 2.0, Etherhash, and Clique).
Its comprehensive permissioning schemes are designed specifically for use in a consortium environment. This is an Ethereum-based technology that enables the development of enterprise-class applications both on the public network and on private or consortium networks. This hybrid approach has allowed Hyperledger Besu to see rapid adoption within the blockchain world.
Hyperledger Besu’s features include
GraphQL HTTP JSON-RPC Service
JSON-RPC WebSocket JSON-RPC Service
Private transaction manager for Private off chain network
Blockchain is a technology that allows businesses to collaborate with new trust models, and lower friction. Removing layers of inefficiency, reconciliation and compensation logic – by recording transactions, data-exchange, and business flows in a shared immutable ledger maintained jointly by the participants in the blockchain network.
However, that does not mean all businesses trust each other to know the details of all of their transactions. Quite the opposite. If trust between organizations was so high as to be able to provide transparent access to internal operations, business models, and infrastructure, there would be no need for a blockchain.
Blockchain also does not remove the need for businesses to conform to regulatory requirements over data and transactions.
So for enterprise blockchain deployments, the reality is that most data must be private to those with a business need-to-know. Not on the “main chain” that is visible to everyone in the network – even when that blockchain is permissioned to only be visible to participants of that business network
Private transaction managers conforming to the Enterprise Ethereum Alliance (EEA) Client Specification allow shared business logic in smart contracts (using normal Ethereum semantics) to be made private to a limited number of participants – making all transactions and state associated with those smart contracts private as well.
All this activity is pinned immutably to the blockchain visible to all participants. The installation of the contract, and each transaction payload, is recorded on the main blockchain via a hash. Participants execute the private transaction, and update their private data, as the hash is ordered and distributed via the blockchain network.
This means the following are irrefutable using the blockchain:
1. What data was sent – the data itself is not visible, but participants with a copy of the private data can recreate the hash at any time
2. The order in which the transactions are executed – sequencing is a critical part of any transactional system, and one of the most important functions performed by a blockchain
The submission of these private transactions is almost identical to a ‘normal’ Ethereum transaction, so this privacy approach is very simple to adopt.
Let us feel this with Corporate B2B Payment with Bank
Let us set up an isolated Ethereum private network with accounts (one for each of the entities - the bank, the buyer, the merchant and demonstrate sending a sample transaction between two of the accounts. Typically, it is recommended running the private network behind a properly configured firewall.
Here private means this network is not connected to Ethereum Mainnet.. Private networks typically use a different chain ID and consensus protocol. Participation in private networks is typically restricted in some way, so the volume of traffic is much lower than Mainnet, resulting in lower system requirements.
Private network system requirements depend on many factors, including:
Step 1 - Install besu
Options : Docker | install Binary | Build from source
Since am using MacOS, am tapping on Brew
Step 2: Node and Data Directories
Create directories for your private network, each of the three nodes, and a data directory for each node: Each node requires a data directory for the blockchain data. When the node starts, Besu saves the node key in this directory.
Step 3 Genesis Block and bootnode
In order to setup a private Ethereum blockchain network (consisting of a single node), we need to initialize and create the Genesis block. The Genesis block is the first block of the blockchain that has no previous block.
Since we are going to use Clique consensus, we must include the address of at least one initial signer in the genesis file. For this Clique network, we'll use Node-1 as the initial signer. This requires obtaining the address for Node-1.
To get the address for Node-1, in the Node-1 directory, use the public-key export-address subcommand to write the node address to the specified file (node1Address in this example).
besu --data-path=data public-key export-address --to=data/node1Address
Let us explain and understand some of the important parameters used in the Genesis block JSON file
The parameter config describes this private blockchain in terms of the network identifier, the consensus engine used, and the block number of the hard forks. The parameter chainId is the blockchain network identifier. A value of 1, 2, or 3 refer to the real-world public Ethereum networks currently in use. Since we desire a private network, we decide to choose an arbitrary value of 1337 for our network. The parameter homesteadBlock with a value of 0 (zero) indicates we want to use the homestead consensus engine, which is the current version of Ethereum.
The parameter parentHash indicates the hash value of the parent block. Since this is the first block, we set it to 0 (zero).
The parameter gasLimit indicates the limit of the gas fees that will be charged for processing a block. Before a transaction is processed, a small processing fee is collected from the initiator by the miner(s). That fees is referred to as gas (also referred to as crypto-fuel) in Ethereum.
The parameter difficulty indicates level of effort for performing the proof-of-work processing. Higher value indicates more effort on the part of the miner nodes. For our private network, we will keep this value low.
The parameter mixhash is the 256-bit hash, that combined with nonce, indicates the amount of computation performed to solve a mathematical puzzle (proof-of-work).
The parameter coinbase (also referred to as etherbase) indicates the address of the account that will receive the rewards for successful mining of a block. Notice that we have selected the first address of the 4 accounts we created for this parameter.
The parameter alloc pre-allocates ethers to the accounts representing bank, buyer, merchant in our private network. In a real chain, the private key should NOT be stored
To initialize our private Ethereum network with the Genesis block, Start the first node as the bootnode with execute the following command:
besu --data-path=data --genesis-file=../cliqueGenesis.json --network-id 1337 --rpc-http-enabled --rpc-http-api=ETH,NET,CLIQUE --host-allowlist="*" --rpc-http-cors-origins="all"
The command line specifies:
Start Peer nodes
besu --data-path=data --genesis-file=../cliqueGenesis.json --bootnodes=<Node-1 Enode URL> --network-id 1337 --p2p-port=30304 --rpc-http-enabled --rpc-http-api=ETH,NET,CLIQUE --host-allowlist="*" --rpc-http-cors-origins="all" --rpc-http-port=8546
Confirm the private network is working
Start another terminal, use curl to call the JSON-RPC API net_peerCount method and confirm the nodes are functioning as peers:
curl -X POST --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}' localhost:8545
Response
{
"jsonrpc" : "2.0",
"id" : 1,
"result" : "0x2"
}
Step 5 : Block explorers
Block explorers are your portal to Ethereum's data. You can use them to see real-time data on blocks, transactions, miners, accounts, and other on-chain activity. Here we use Ethereum Lite Explorer
The block explorer displays a summary of the private network, indicating peers.
Since stage is ready, lets do some dance with smart contract to interact with the network
Step 6- Smart Contract with Solidity
Let get ready with SC Local Dev Environment it's the same as normal app development in which you have to set up your local environment, database before coding.
We will use Truffle to create an environment to develop smart contracts on the Ethereum blockchain. You will need Node.js installed on your computer first to install the Truffle package.
Install Truffle
Navigate to any folder, open your terminal, and type npm install -g truffle. This command will install the truffle package on your machine. You could verify if it’s installed successfully by typing truffle version
Create Truffle Project
Next type truffle init to create our Ethereum blockchain projec with the following
You can install Ganache which is a simulated Ethereum blockchain on our local machine. Ganache allows us to perform actions on our Blockchain locally without having to deploy it to the real Ethereum network.
Let us see how this changes the way we current application development
Dapps - Micro Applications to Decentralized Applications
Writing the smart contract¶
We'll start our dapp by writing the smart contract that acts as the back-end logic and storage.
Create a new file named Purchase.sol in the contracts/ directory and add the following content to the file:
Recommended by LinkedIn
pragma solidity ^0.5.0;
contract Purchase {
}
The minimum version of Solidity required is noted at the top of the contract: pragma solidity ^0.5.0;. The pragma command means "additional information that only the compiler cares about", while the caret symbol (^) means "the version indicated or higher".
Like JavaScript or PHP, statements are terminated with semicolons.
Variable setup¶
Solidity is a statically-typed language, meaning data types like strings, integers, and arrays must be defined. Solidity has a unique type called an address. Addresses are Ethereum addresses, stored as 20 byte values. Every account and smart contract on the Ethereum blockchain has an address and can send and receive Ether to and from this address.
Add the following variable on the next line after contract Purchase {.
address[16] public owners
We've defined a single variable: owners. This is an array of Ethereum addresses. Arrays contain one type and can have a fixed or variable length. In this case the type is address and the length is 16.
Your first function: Purchasing a NFT
Let's allow users to make their own requests. Add the following function to the smart contract after the variable declaration we set up above.
// Owning nft
function own(uint nftId) public returns (uint) {
require(nftId >= 0 && nftId <= 15);
owners[nftId] = msg.sender;
return nftId;
}
In Solidity the types of both the function parameters and output must be specified. In this case we'll be taking in a nftId (integer) and returning an integer.
We are checking to make sure nftId is in range of our owners array. Arrays in Solidity are indexed from 0, so the ID value will need to be between 0 and 15. We use the require() statement to ensure the ID is within range.
If the ID is in range, we then add the address that made the call to our owners array. The address of the person or smart contract who called this function is denoted by msg.sender.
Finally, we return the nftId provided as a confirmation.
Your second function: Retrieving the owners As mentioned above, array getters return only a single value from a given key. Our UI needs to update all nft purchase statuses, but making 16 API calls is not ideal. So our next step is to write a function to return the entire array.
Add the following getOwners() function to the smart contract, after the own() function we added above:
// Retrieving the owners
function getOwners() public view returns (address[16] memory) {
return owners;
}
Since the owner is already declared, we can simply return it. Be sure to specify the return type (in this case, the type for owners) as address[16] memory. memory gives the data location for the variable.
The view keyword in the function declaration means that the function will not modify the state of the contract. Further information about the exact limits imposed by view is available here.
Compiling and migrating the smart contract
Now that we have written our smart contract, the next steps are to compile and migrate it.
Compilation Solidity is a compiled language, meaning we need to compile our Solidity to bytecode for the Ethereum Virtual Machine (EVM) to execute. Think of it as translating our human-readable Solidity into something the EVM understands.
In a terminal, make sure you are in the root of the directory that contains the dapp and type:
truffle compile
You should see output similar to the following:
Compiling your contracts...
===========================
> Compiling ./contracts/Purchase.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to ../build/contracts
> Compiled successfully using:
- solc: 0.5.0+commit.1d4f565a.Emscripten.clang
Migration
Now that we've successfully compiled our contracts, it's time to migrate them to the blockchain! A migration is a deployment script meant to alter the state of your application's contracts, moving it from one state to the next. For the first migration, you might just be deploying new code, but over time, other migrations might move data around or replace a contract with a new one.
You'll see one JavaScript file already in the migrations/ directory: 1_initial_migration.js. This handles deploying the Migrations.sol contract to observe subsequent smart contract migrations, and ensures we don't double-migrate unchanged contracts in the future.
Now we are ready to create our own migration script. Create a new file named 2_deploy_contracts.js in the migrations/ directory.
Add the following content to the 2_deploy_contracts.js file:
var Purchase = artifacts.require("Purchase");
module.exports = function(deployer) {
deployer.deploy(Purchase);
};
Creating a user interface to interact with the smart contract
Now that we've created the smart contract, deployed it to our local test blockchain and confirmed we can interact with it via the console, it's time to create a UI so that NFT has something to use for his NFT shop! Included with the nft-shop Truffle Box was code for the app's front-end. That code exists within the src/ directory.
The front-end doesn't use a build system (webpack, grunt, etc.) to be as easy as possible to get started. The structure of the app is already there; we'll be filling in the functions which are unique to Ethereum. This way, you can take this knowledge and apply it to your own front-end development.
Open /src/js/app.js in a visual studio code editor. add the following
markOwned : function(owners, account) {
var purchaseInstance;
App.contracts.Purchase.deployed().then(function(instance) {
purchaseInstance = instance;
console.log("purchaseInstance:"+purchaseInstance);
return purchaseInstance.getOwners.call();
}).then(function(owners) {
for (i = 0; i < owners.length; i++) {
if (owners[i] !== '0x0000000000000000000000000000000000000000') {
$('.panel-ntf').eq(i).find('button').text('Success').attr('disabled', true);
}
}
}).catch(function(err) {
console.log(err.message);
});
},
Handling the own() Function¶
handleOwn : function(event) {
event.preventDefault();
var nftId = parseInt($(event.target).data('id'));
var purchaseInstance;
web3.eth.getAccounts(function(error, accounts) {
if (error) {
console.log(error);
}
var account = accounts[0];
console.log(" App.contracts.Purchase.deployed():"+App.contracts.Purchase.deployed());
App.contracts.Purchase.deployed().then(function(instance) {
purchaseInstance = instance;
// Execute own as a transaction by sending account
console.log(" Execute own as a transaction by sending account:"+account);
return purchaseInstance.own(nftId, {from: account});
}).then(function(result) {
return App.markOwned();
}).catch(function(err) {
console.log(err.message);
});
});
}
In the browser where you have MetaMask enabled and one of the test accounts loaded, open a new tab and navigate to the Sample NFT Shop dapp where you can own lovely nft (sorry, not for real, it's a demo).
When you click on OWN, a MetaMask window will pop up and request your permissions to continue with the transaction.
In the Block explorer, we can trace new tx
Node level terminal , it shows the transaction as well
The MetMask UI also keeps a record of the transaction.
Let us try to send out ETH to outside the private network e.g. external account e.g. Jerry
Once its submitted, you can see the transaction being failed which is the negative test we wanted to prove
If you look at the block explorer, you can see the details on he errors
Deployment
Finally, let also take a look at the flexibility here for the production deployment,. It Ready-to-use scripts to enable production-ready, highly available networks.
● Ansible
● Docker
● Kubernetes
● Terraform
● AWS
● Azure
Blockchain networks require different types of nodes – validators, bootnodes, and normal network nodes, so you can configure those arrangements easily for your cluster. Deploy Hyperledger Besu nodes with ease using the deployment tool of your Choice
We have taken peek look into some of the basics .. This can co exists with current technology used to build existing systems as they share some characteristics. For instance micro-service, cloud-native architecture, uses open application programming interfaces (APIs) to integrate with legacy architecture and share information. Together these differ from traditional payments systems that rely on a monolithic architecture, which is brittle and makes small changes expensive to implement.
Blockchain has entered the discussion as a way to address a challenge that existing technologies have not yet been able to solve: inefficiency of processing costs. Currently, RTPS requires that banks settle transactions several times per day instead of once. This multiplies processing costs. Decentralization enables different financial institutions to connect to the same ledger. This one change can increase transactional efficiency.
As RPTS scales globally, actors will rely less and less on the traditional role of correspondent banking. And for those systems that include blockchain, they will further remove the need for the nostro accounts associated with correspondent banking and the need to pre-fund these accounts
Soon, there are a few emerging trends in the payments :
• CBDC and its potential to be used for settlement for interbank payments, both domestically and internationally, as well as for retail payments.
• An increased focus on overlay services such as Request to Pay (R2P) and aliases. R2P overlays on RTPS will improve efficiency and speed of payments